---
title: "初学关键段容易忽略的问题"
author: "J2EE大鸟"
date: "2013-11-22T15:01:19Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-11-22T15:01:19Z"
id: 1979435
url: "https://benworld.iteye.com/blog/1979435"
---

今天遇到了一个初学关键段的问题，在多线程运行条件下，关键段总是遇到异常，先说一说代码

```
#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;
}
```

运行结果很容易让人感觉奇怪，如下：

![](http://dl2.iteye.com/upload/attachment/0091/4243/96d6548b-70f9-358f-b34d-94521168e91a.png)  
 

进入关键段产生不能处理的异常，

认真分析，得出结论： 主线程中的关键段在子线程还没有完全创建完成之前提前关闭。

加入一个多线程的等待线程即可。

```
for(i=0; i<NUM; i++) {
		handles[i] = (HANDLE) _beginthreadex(NULL, 0, funcTh, &i, 0, NULL);
	}
	WaitForMultipleObjects(NUM, handles, true, INFINITE);
```

 

运行正常：

![](http://dl2.iteye.com/upload/attachment/0091/4241/386d4903-582d-39c8-afe0-63b74f3ea5f0.png)  
 

注： 因为子线程之间没有采用同步处理，故输出的值是乱的。