WaitForSingleObject and max. waiting threads
I just noticed the following phrase in one the Intel's articles:
One disadvantage of WaitForSingleObject is that it will always obtain a kernel lock, so it enters privileged mode (ring 0) whether the lock is achieved or not. This API also enters the Windows kernel even if a 0 timeout is specified. Another disadvantage of this method of locking is that it can only handle 64 threads attempting to place a lock on an object at once
If I understood it correctly, this code has a UB in it:
#include <Windows.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#define THREAD_COUNT 100
HANDLE g_mutex;
DWORD WINAPI foo(LPVOID lpParameter)
{
WaitForSingleObject(g_mutex, INFINITE);
return 0;
}
int main()
{
g_mutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
if (g_mutex == NULL)
{
return EXIT_FAILURE;
}
WaitForSingleObject(g_mutex, INFINITE);
std::vector<HANDLE> threads;
for (int i = 0; i < THREAD_COUNT; i++)
{
HANDLE th = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE)foo,
NULL, // no thread function arguments
0, // default creation flags
NULL); // don't receive thread identifier
if (th == NULL)
{
return EXIT_FAILURE;
}
threads.push_back(th);
}
while (true)
{
Sleep(100);
}
}
because it forces more than 64 threads to wait for the specific resource (in my case, mutex).
I know that this limitation exists for the WaitForMultipleObjects function, but in the article it says about the WaitForSingleObject function.
Am I right?
链接地址: http://www.djcxy.com/p/62482.html