Began to superficially study multithreading. I wrote a small code.

Function for each thread:

DWORD WINAPI increment(CONST LPVOID lpParam) { CONST HANDLE hMutex = (CONST HANDLE)lpParam; while (testMutex < testMax) { WaitForSingleObject(hMutex, INFINITE); testMutex++; if(testMutex<testMax) std::cout << testMutex << std::endl; ReleaseMutex(hMutex); } ExitThread(0); } 

And the thread creation function itself:

 void createMutexAndThread() { HANDLE hMutex = CreateMutex(NULL, FALSE, NULL); HANDLE hThreads[500]; for (int i = 0; i < 500; i++) { hThreads[i] = CreateThread(NULL, 0, &increment, hMutex, 0, NULL); } WaitForSingleObject(hThreads[0], INFINITE); //WaitForMultipleObjects(64, hThreads, TRUE, INFINITE); std::cout << "1\n"; for (int i = 0; i < 500; i++) { CloseHandle(hThreads[i]); } } 

The mutex is unlocked on the ReleaseMutex(...) function, but on which line in the increment function will the mutex be blocked?

    1 answer 1

    The WaitForSingleObject function waits for the mutex to be released and occupies it itself.