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?