Is there a thread limit EnterCriticalSection() can cope with?
The following code works fine with 64 threads, but it crashes when using 65 or more:
CRITICAL_SECTION TestCritSection;
unsigned int threadId;
int getThreadId()
{
int tid = -1;
EnterCriticalSection(&TestCritSection);
tid= threadId;
threadId++;
LeaveCriticalSection(&TestCritSection);
return tid;
}
void parallelTest()
{
int tid = getThreadId();
cout << "Thread " << tid << " executed" << endl;
}
void
multiThreadTest()
{
unsigned int numThreads = 64; // fine, but program crashes when numThreads is set to 65 or more
HANDLE *threads = new HANDLE[numThreads];
DWORD ThreadID;
threadId = 1;
if (!InitializeCriticalSectionAndSpinCount(&TestCritSection, 0x00000400)) return;
for (int i=0; i<numThreads; ++i)
{
threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) parallelTest, (LPVOID) NULL, 0, &ThreadID);
}
WaitForMultipleObjects(numThreads, threads, TRUE, INFINITE);
DeleteCriticalSection(&TestCritSection);
for (int i=0; i<numThreads; ++i)
{
CloseHandle(threads[i]);
}
delete [] threads;
}
I guess CRITICAL_SECTION is internally using a semaphore with a max count of 64.
Can I somehow change that?
As nobody wants to answer my question, I will do it myself based on HansPassant’s comment to my question.
He pointed out that the problem is
WaitForMultipleObjects(), which takes a parameter(from msdn)
MAXIMUM_WAIT_OBJECTSis defined as 64, more informations in this thread.This means: yes, there is a hard-coded limit on the amount of threads, but the restriction is not on
EnterCriticalSectionbut onWaitForMultipleObjects, which returns an error code I should have checked.Here is more information on how to get more than 64 threads working in parallel.