// sparksandflames.com #include #include #include #include #include #include HANDLE mutexObject; int tcnt = 4; // Number of threads to start int threadsStarted; // Number of threads started double f[100]; void WinThreadFunction( void *argPointer ) { int w; int i,j; int tot; int x = 100000; // GET THREAD INDEX w = (int ) argPointer; f[w] = 0 ; // INCREASE THREAD COUNT WaitForSingleObject( mutexObject, INFINITE ); threadsStarted++; printf("Start Thread = %d Count = %d\n",w,threadsStarted); ReleaseMutex(mutexObject); // DO SOME BUSY WORK THE COMPILER WON'T OPTIMIZE AWAY tot = 0; for(i=0;ix*x %d %d\n",i,x*x); fflush(stdout); // DECREASE COUNT WaitForSingleObject( mutexObject, INFINITE ); threadsStarted--; ReleaseMutex(mutexObject); // SEE HOW EVEN THE WORKLOAD IS printf("Stop Thread = %d Remaining = %d\n",w,threadsStarted); for(i=0;i 100 ) { printf("winthread('%d'): Thread count must be between 1 - 100\n",tcnt); return 0; } } printf("%d threads\n",tcnt); /* Start Timers */ wallstart = time(NULL); start = clock(); /* Reset thread count. */ threadsStarted = 0; /* Create the mutex */ threadsStarted = 0; mutexObject = CreateMutex( NULL, FALSE, NULL ); /* Cleared */ if(mutexObject == NULL && GetLastError() != ERROR_SUCCESS) { printf("failed to obtain a proper mutex for multithreaded application"); exit(1); } // START TCNT THREADS for(ix=0;ix < tcnt; ix++) a[ix] = (HANDLE) _beginthread( WinThreadFunction, 0, (void *) ix ); // WAIT FOR TCNT THREADS TO FINISH WaitForMultipleObjects(tcnt, a, TRUE, INFINITE); CloseHandle( mutexObject ); // RUNTIMES end = clock(); wallend = time(NULL); printf("Elapsed time: %lu clocks %lu seconds", end - start, wallend - wallstart); return 0; }