6. Parallel Implementation - wait for first using pipe
pthread_pipe.c:// 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 <string.h> #include <pthread.h> #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]); } --- $ gcc -std=c11 -pedantic -Wall -g -O -o pthread_pipe pthread_pipe.c -pthread $ time ./pthread_pipe f 0 start = 0, size = 6 f 1 start = 10, size = 5 f 3 start = 30, size = 3 f 2 start = 20, size = 4 f 3 done real 0m3.004s user 0m0.003s sys 0m0.002s