// The program illustrates the creation // of threads and the usage of a mutex. // It creates 2 threads with the same starting function. // The first thread prints 10 times the word "Heads", // the second thread prints 10 times the word "Tails". // Between prints each thread sleeps a random // time up to 2 sec. The last printed word // (Heads or Tails) is the result of the draw. // // The mutex is used to exclude simultaneous // prints by different threads. #include #include #include // Thread body function DWORD WINAPI run(void* arg); static HANDLE hMutex = NULL; int main() { HANDLE hThread1, hThread2; DWORD threadID1, threadID2; const char *heads = "Heads"; const char *tails = "Tails"; int curtime = (int) GetTickCount(); srand(curtime); // Set the random generator // Create the mutex hMutex = CreateMutex( NULL, // default security attributes FALSE, // initially not owned NULL // unnamed mutex ); if (hMutex == NULL) { printf("Cannot create a mutex: error %d\n", GetLastError()); exit(-1); } // Create the first thread hThread1 = CreateThread( NULL, // lpThreadAttributes 0, // dwStackSize - default &run, // thread starting function (void *) heads, // parameter of thread starting function 0, // dwCreationFlags &threadID1 ); if (hThread1 == NULL) { printf("Cannot create thread 1: error %d\n", GetLastError()); exit(-1); } WaitForSingleObject(hMutex, INFINITE); printf("Thread 1 is created.\n"); ReleaseMutex(hMutex); // Create the second thread hThread2 = CreateThread( NULL, // lpThreadAttributes 0, // dwStackSize - default &run, // thread starting function (void *) tails, // parameter of thread starting function 0, // dwCreationFlags &threadID2 ); if (hThread2 == NULL) { printf("Cannot create thread 2: error %d\n", GetLastError()); exit(-1); } WaitForSingleObject(hMutex, INFINITE); printf("Thread 2 is created.\n"); ReleaseMutex(hMutex); // Wait until threads terminate WaitForSingleObject(hThread1, INFINITE); WaitForSingleObject(hThread2, INFINITE); CloseHandle(hThread1); CloseHandle(hThread2); CloseHandle(hMutex); return 0; } DWORD WINAPI run(void* arg) { int i; const char *txt = (const char *) arg; for (i = 0; i < 10; i++) { WaitForSingleObject(hMutex, INFINITE); printf("%s\n", txt); ReleaseMutex(hMutex); int t = rand()%2000 + 1; // Random time in millisec Sleep(t); } return 0; }