// threads using pipe // #include #include #include // for sleep() and pipe() #include // for exit() #define EXIT(msg) { perror(msg); exit(1); } #define Pthread_create(a,b,c,d) if( pthread_create(a,b,c,d) ) EXIT("pthread_create") #define Pipe(a) if( pipe(a) ) EXIT("pipe") #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 printf( "Done\n"); fflush(stdout); return 0; } int main( void) { pthread_t t[NT]; // redirect stdin and stdout through pipe // int fd[2]; Pipe(fd); dup2(fd[0],0); dup2(fd[1],1); close(fd[0]); close(fd[1]); // create the threads // for( int i = 0; i < NT; ++i) Pthread_create( &t[i], 0, f, &count[i]); // wait until any one thread is finished // char line[BUFSIZ]; (void) !fgets( line, BUFSIZ, stdin); // ignore fgets() return value // stop all threads // for( int i = 0; i < NT; ++i) pthread_cancel( t[i]); }