// test pthread_create() and sched_yield() // #include #include #include // for sleep() #include // for sched_yield() #define NT 4 // number of threads int count[NT] = { 5, 4, 3, 2 }; void *f( void *v) { int *p = v; while( *p > 0) { sleep(1); --*p; } // slowly decrement my counter return 0; } int main( void) { pthread_t t[NT]; // create the threads // for( int i = 0; i < NT; ++i) if( pthread_create( &t[i], 0, f, &count[i]) ) { perror( "pthread_create"); return 1; } // wait // while(1) { int done = 0; for( int i = 0; i < NT; ++i) if( count[i] == 0) ++done; // if( done == NT) break; // wait until all threads are finished if( done > 0) break; // wait until any one thread is finished sched_yield(); } // stop all threads // for( int i = 0; i < NT; ++i) pthread_cancel( t[i]); }