// sparksandflames.com #include #include #include int main(int argc, char *argv[]); void *UNIXThreadFunction( void *argPointer ); pthread_mutex_t mutexObject = PTHREAD_MUTEX_INITIALIZER; int threadsStarted=0; int tcnt=4; double f[100]; int main(int argc, char *argv[]) { int rc; int count = 0; time_t wallstart,wallend; double timework; pthread_t threads[100]; // PARAMETER 1 OVER RIDES DEFAULT if (argc == 2) { tcnt = atoi(argv[1]); if (tcnt < 1 || tcnt > 100 ) { printf("unixthread('%d'): Thread count must be between 1 - 100\n",tcnt); return 0; } } printf("%d threads\n",tcnt); // START TIMER wallstart = time(NULL); // START TCNT THREADS while(count < tcnt) { rc = pthread_create(&threads[count], NULL, &UNIXThreadFunction,(void *) count); if(rc) { printf("thread creation failed\n"); exit(1); } count++; } // WAIT FOR TCNT THREADS TO FINISH while( count >= 0) { pthread_join( threads[count], NULL); count--; } // STOP TIMER. wallend = time(NULL); timework = wallend - wallstart; // DISPLAY STATS printf("Elapsed time: %.0f seconds\n", timework); exit(0); } void *UNIXThreadFunction( void *argPointer ) { int w; int i,j; int tot; int x = 100000; int savestarted; // GET THREAD INDEX w = (int ) argPointer; f[w] = 0 ; // INCREASE THREAD COUNT pthread_mutex_lock( &mutexObject ); threadsStarted++; savestarted = threadsStarted; pthread_mutex_unlock( &mutexObject ); // DISPLAY TRACE printf("Start Thread = %d Count = %d\n",w,savestarted); fflush(stdout); // DO SOME BUSY WORK THE COMPILER WON'T OPTIMIZE AWAY tot = 0; for(i=0;ix*x %d %d\n",w,i,x*x); fflush(stdout); } // DECREASE THREAD COUNT pthread_mutex_lock( &mutexObject ); threadsStarted--; savestarted = threadsStarted; pthread_mutex_unlock( &mutexObject ); printf("End Thread = %d Count = %d\n",w,savestarted); // SEE HOW EVEN THE WORKLOAD IS for(i=0;i