/** * A simple pthread program illustrating RT pthread scheduling. * * Figure 6.20 * * To compile: * * gcc posix-rt.c -o posix-rt -lpthread * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Ninth Edition * Copyright John Wiley & Sons - 2013. * * Revised by X. Meng for classroom demo * CSCI 315, fall 2013 */ #include #include #define NUM_THREADS 50 /* the thread runs in this function */ void *runner(void *param); /* get the current scheduling policy */ void show_policy(pthread_attr_t * attr, int * policy) { int policy_cp; if (pthread_attr_getschedpolicy(attr,&policy_cp) != 0) fprintf(stderr, "Unable to get policy.\n"); else { if (policy_cp == SCHED_OTHER) printf("SCHED_OTHER\n"); else if (policy_cp == SCHED_RR) printf("SCHED_OTHER\n"); else if (policy_cp == SCHED_FIFO) printf("SCHED_FIFO\n"); } (*policy) = policy_cp; } void print_sched_policy() { printf("Possible scheduling policies \n"); printf("SCHED_OTHER %d\n", SCHED_OTHER); printf("SCHED_RR %d\n", SCHED_RR); printf("SCHED_FIFO %d\n", SCHED_FIFO); } int main(int argc, char *argv[]) { int i, policy; pthread_t tid[NUM_THREADS]; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */ print_sched_policy(); /* get the default attributes */ pthread_attr_init(&attr); /* get the current scheduling policy */ show_policy(&attr, &policy); /* set the scheduling policy - FIFO, RT, or OTHER */ // if (pthread_attr_setschedpolicy(&attr, SCHED_OTHER) != 0) // printf("unable to set scheduling policy to SCHED_OTHER \n"); if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0) printf("unable to set scheduling policy to SCHED_FIFO \n"); // if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0) // printf("unable to set scheduling policy to SCHED_RR \n"); /* get the current scheduling policy */ show_policy(&attr, &policy); /* 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) { 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); }