EnterCriticalSection() 是否有线程限制?以下代码适用于 64 个线程,但在使用 65 个或更多线程时会崩溃:
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;
}
我猜 CRITICAL_SECTION 在内部使用最大计数为 64 的信号量。我能以某种方式改变它吗?