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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?