How do I use threads and synchronization primitives on Windows in C++?

Using threads and synchronization primitives in Windows with C++ involves utilizing the Windows API, which provides a rich set of tools for multithreading. This includes creating threads, using mutexes, and other synchronization mechanisms to prevent race conditions.

Here is a simple example of how to create a thread and use a mutex for synchronization in C++ on Windows:

#include #include HANDLE hMutex; int sharedResource = 0; DWORD WINAPI ThreadFunction(LPVOID lpParam) { for (int i = 0; i < 5; i++) { WaitForSingleObject(hMutex, INFINITE); // Wait for the mutex // Critical section sharedResource++; std::cout << "Thread ID: " << GetCurrentThreadId() << ", Shared Resource: " << sharedResource << std::endl; ReleaseMutex(hMutex); // Release the mutex Sleep(100); // Sleep for a bit to simulate work } return 0; } int main() { hMutex = CreateMutex(NULL, FALSE, NULL); // Create a mutex HANDLE hThreads[2]; for (int i = 0; i < 2; i++) { hThreads[i] = CreateThread(NULL, 0, ThreadFunction, NULL, 0, NULL); // Create threads } WaitForMultipleObjects(2, hThreads, TRUE, INFINITE); // Wait for threads to finish CloseHandle(hMutex); // Clean up for (int i = 0; i < 2; i++) { CloseHandle(hThreads[i]); } return 0; }

C++ threads Windows API synchronization mutex multithreading