/** * A simple pthread program illustrating POSIX scheduling. * * Figure 6.8 * * To compile: * * gcc posix-sched.c -o posix-sched -lpthread * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Ninth Edition * Copyright John Wiley & Sons - 2013. * * Revised by X. Meng for class demo * CSCI 315, fall 2013 */ #include #include #define NUM_THREADS 5 /* the thread runs in this function */ void *runner(void *param); main(int argc, char *argv[]) { int i, scope; pthread_t tid[NUM_THREADS]; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */ /* get the default attributes */ pthread_attr_init(&attr); /* first inquire on the current scope */ if (pthread_attr_getscope(&attr,&scope) != 0) fprintf(stderr, "Unable to get scheduling scope.\n"); else { if (scope == PTHREAD_SCOPE_PROCESS) printf("PTHREAD_SCOPE_PROCESS\n"); else if (scope == PTHREAD_SCOPE_SYSTEM) printf("PTHREAD_SCOPE_SYSTEM\n"); else fprintf(stderr,"Illegal scope value.\n"); } /* set the scheduling algorithm to PCS or SCS */ if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0) printf("unable to set scheduling policy.\n"); // we can't set PTHREAD_SCOPE_PROCESS /* if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS) != 0) printf("unable to set scheduling policy.\n"); */ /* create the threads */ for (i = 0; i < NUM_THREADS; i++) pthread_create(&tid[i],&attr,runner,NULL); /** * Now join on each thread */ for (i = 0; i < NUM_THREADS; i++) pthread_join(tid[i], NULL); } /** * The thread will begin control in this function. */ void *runner(void *param) { /* do some work ... */ int i; double j = 0; /* do some work ... */ while(j < 10000) { for (i = 0; i < 100000; i ++); usleep(10); j = j + 1; } pthread_exit(0); }