今天遇到了一个初学关键段的问题,在多线程运行条件下,关键段总是遇到异常,先说一说代码
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
const int NUM = 10;
HANDLE semaphore;
CRITICAL_SECTION sc;
unsigned int __stdcall funcTh(PVOID pm) {
int a = *((int *) pm);
EnterCriticalSection(&sc);
cout << a << endl;
LeaveCriticalSection(&sc);
return 0;
}
int main() {
HANDLE handles[NUM];
semaphore = CreateSemaphore(NULL, 0, 1, NULL);
InitializeCriticalSection(&sc);
int i;
for(i=0; i<NUM; i++) {
handles[i] = (HANDLE) _beginthreadex(NULL, 0, funcTh, &i, 0, NULL);
}
DeleteCriticalSection(&sc);
CloseHandle(semaphore);
getchar();
return 0;
}
运行结果很容易让人感觉奇怪,如下:
进入关键段产生不能处理的异常,
认真分析,得出结论: 主线程中的关键段在子线程还没有完全创建完成之前提前关闭。
加入一个多线程的等待线程即可。
for(i=0; i<NUM; i++) {
handles[i] = (HANDLE) _beginthreadex(NULL, 0, funcTh, &i, 0, NULL);
}
WaitForMultipleObjects(NUM, handles, true, INFINITE);
运行正常:
注: 因为子线程之间没有采用同步处理,故输出的值是乱的。