/* % cc -Xa -v -o priority.c -o prtest -lpthread -lposix4 The main rotuine of this program creates 3 instances of "tester" threads. Each of these are given different priorities. Higher number means higher priority. All these three theads wait at a semaphore called "stop" whose initial value is 0. The main routine signals the "stop" semaphore 3 times. The highest priority waiting thread is resumed first. This program shows how to set or get the priority of a thread */ #include #include #include #include #include #define HIGH 30 #define MID 20 #define LOW 10 pthread_mutex_t prt_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t prt_cv = PTHREAD_COND_INITIALIZER; int prt = 0; sem_t stop; /* high priority thread */ void * tester ( void *arg ) { pthread_t myid; int my_pr; int policy; struct sched_param prm; myid = pthread_self(); pthread_getschedparam(myid, &policy, &prm); my_pr = prm.sched_priority; printf( "Tester Thread %d of priority %d waiting at stop\n", myid, my_pr ); sem_wait( &stop ); printf( "Tester Thread %d of priority %d resumed from stop\n", myid, my_pr ); } /* main - start here. */ main( int argc, char *argv[] ) { int i; int n; pthread_attr_t attr; pthread_t tid; struct sched_param param; printf( "Main started\n" ); /* Initialize the value of the semaphore to 0 (third arg) */ sem_init( &stop, 0, 0); pthread_attr_init( &attr ); param.sched_priority = MID; pthread_attr_setschedparam( &attr, ¶m); pthread_attr_setschedpolicy( &attr, SCHED_FIFO); if ( n = pthread_create( &tid, &attr, tester, NULL ) ) { fprintf( stderr, "pthread_create: %s\n", strerror( n ) ); exit( 1 ); } param.sched_priority = MID; pthread_attr_setschedparam( &attr, ¶m); if ( n = pthread_create( &tid, &attr, tester, NULL ) ) { fprintf( stderr, "pthread_create: %s\n", strerror( n ) ); exit( 1 ); } param.sched_priority = MID; pthread_attr_setschedparam( &attr, ¶m); if ( n = pthread_create( &tid, &attr, tester, NULL ) ) { fprintf( stderr, "pthread_create: %s\n", strerror( n ) ); exit( 1 ); } pthread_attr_destroy( &attr ); sem_post( &stop ); pthread_join(tid, NULL); printf( "Main returned \n" ); return( 0 ); }