// The program illustrates the creation // of threads and the usage of a critical section. // 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 critical section object is used to exclude // simultaneous prints by different threads. #include #include #include // Thread body function DWORD WINAPI run(void* arg); static CRITICAL_SECTION critSect; 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 InitializeCriticalSection(&critSect); // 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); } EnterCriticalSection(&critSect); printf("Thread 1 is created.\n"); LeaveCriticalSection(&critSect); // 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); } EnterCriticalSection(&critSect); printf("Thread 2 is created.\n"); LeaveCriticalSection(&critSect); // Wait until threads terminate WaitForSingleObject(hThread1, INFINITE); WaitForSingleObject(hThread2, INFINITE); CloseHandle(hThread1); CloseHandle(hThread2); DeleteCriticalSection(&critSect); return 0; } DWORD WINAPI run(void* arg) { int i; const char *txt = (const char *) arg; for (i = 0; i < 10; i++) { EnterCriticalSection(&critSect); printf("%s\n", txt); LeaveCriticalSection(&critSect); int t = rand()%2000 + 1; // Random time in millisec Sleep(t); } return 0; }