// run a function in parallel N times, wait for the first one to finish // // using a pipe for thread communication // // run time is minimum of the run times for each function call // #include #include #include "common.c" // to avoid stdio buffering on the pipe, must make stdout unbuffered // or do fflush(stdout) after every printf() // setbuf( stdout, 0); // make stdout unbuffered // redirect stdin and stdout through pipe // int fd[2]; if( pipe(fd)) { perror("pipe"); return 1; } dup2(fd[0],0); dup2(fd[1],1); close(fd[0]); close(fd[1]); // start the threads // pthread_t t[N]; for( int i = 0; i < N; ++i) if( pthread_create( &t[i], 0, f, &D[i].i ) ) { perror( "pthread_create"); return 1; } // wait until any one thread is finished // char msg[BUFSIZ]; while( fgets( msg, BUFSIZ, stdin) ) { fputs( msg, stderr); // copy thread messages to stderr if( strstr( msg, "done") ) break; } // stop all threads // for( int i = 0; i < N; ++i) pthread_cancel( t[i]); }