C++ EnterCriticalSection因超过64个线程而崩溃
EnterCriticalSection()是否有线程限制? 以下代码适用于64个线程,但在使用65个或更多线程时崩溃:C++ EnterCriticalSection因超过64个线程而崩溃,c++,windows,multithreading,winapi,C++,Windows,Multithreading,Winapi,EnterCriticalSection()是否有线程限制? 以下代码适用于64个线程,但在使用65个或更多线程时崩溃: CRITICAL_SECTION TestCritSection; unsigned int threadId; int getThreadId() { int tid = -1; EnterCriticalSection(&TestCritSection); tid= threadId; threadId++; Le
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_段TestCritSection;
无符号int-threadId;
int getThreadId()
{
int-tid=-1;
EnterCriticalSection(&TestCriticalSection);
tid=螺纹ID;
threadId++;
LeaveCriticalSection(&TestCriticalSection);
返回tid;
}
无效测试()
{
int tid=getThreadId();
因为没有人愿意回答我的问题,我会根据汉帕桑对我问题的评论自己回答
他指出问题在于WaitForMultipleObjects()
,它接受一个参数
n计数[单位]
The number of object handles in the array pointed to by lpHandles.
对象句柄的最大数目是maximum\u WAIT\u对象。此
参数不能为零
(来自)
最大等待对象
定义为64,线程中的更多信息
这意味着:是的,线程数量有硬编码限制,但限制不在EnterCriticalSection
上,而是在WaitForMultipleObjects
上,它返回我应该检查的错误代码
是关于如何使64个以上线程并行工作的更多信息。问题在于WaitForMultipleObjects,而不是关键部分。永远不要忽略api函数返回值。阅读材料:哦……我没有想到这一点。因此限制是最大等待对象…@Steve-o:感谢链接!我也觉得有必要指出t拥有比虚拟内核更多线程的hat不太可能提高性能(并且可能会损害性能)——归根结底,系统一次只能做一件事。