---
title: "终止运行线程的注意事项"
author: "J2EE大鸟"
date: "2013-11-06T15:51:21Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-11-06T15:51:54Z"
id: 1972121
url: "https://benworld.iteye.com/blog/1972121"
---

终止运行线程

1\. 线程函数返回。

2\. 线程通过调用ExitThread函数“杀死”自己（避免使用）。

3\. 同一个进程或另一个进程中的线程调用TerminateThread函数（避免使用）

4\. 包含线程的进程终止运行（避免使用）

 

**让线程函数返回，可以确保：**

**1. 线程函数中创建的所有C++对象都通过其析构函数被正确的销毁；**

**2. 操作系统正确释放线程栈使用的内存；**

**3. 操作系统把线程的退出代码设为线程函数的返回值；**

**4. 系统递减少线程的内核对象的使用计数。**

 

使用ExitThread函数终止线程，并导致操作系统清理该线程使用的所有操作系统资源。但是，C++资源不会被回收。

不同于ExitThread总是“杀死”主调线程，TerminateThread能杀死任何线程，但是，线程无法正确清理，而且不能阻止自己被终止运行。详见《windows核心编程》P149。

 

ExitThread举例：

```
#include <iostream>
#include <windows.h>
#include <process.h>

using namespace std;
unsigned int last_handle;

unsigned int __stdcall lastFunc(PVOID pm) {
	cout << "hello world hello kitty" << endl;
	Sleep(2000);
	_endthreadex(last_handle);
	cout << "hello world" << endl;
	return 0;
}

int main() {
	last_handle = _beginthreadex(NULL, 0, lastFunc, NULL, 0, NULL);
	Sleep(500);
	
	cout << "to be end..." << endl;

	getchar();
	return 0;
}
```

运行结果为：

![](http://dl2.iteye.com/upload/attachment/0090/9195/786c4e80-a787-3b5d-92c8-02d46a312f46.png)  
 

线程函数 终止自己。

 

```
#include <iostream>
#include <windows.h>
#include <process.h>

using namespace std;

unsigned int last_handle;

unsigned int __stdcall lastFunc(PVOID pm) {
	cout << "hello world hello kitty" << endl;

	Sleep(2000);
	cout << "hello world" << endl;
	return 0;
}

int main() {
	last_handle = _beginthreadex(NULL, 0, lastFunc, NULL, 0, NULL);
	_endthreadex(last_handle);

	Sleep(500);
	
	cout << "to be end..." << endl;
	getchar();
	return 0;
}
```

运行结果如下：

![](http://dl2.iteye.com/upload/attachment/0090/9202/dd78e6b7-b8db-34e7-9cac-f23cb16ae286.png)  
 显示出运行窗口之后，窗口自动消失

在主线程中调用了\_endthreadex(last\_handle);  会保证该 last\_handle 线程完成后， 主线程终止。

比较让人奇怪的是 传入的是子线程的句柄，子线程非但不终止 而且 主线程在等待子线程结束后，终止了自己。

 

即\_endthreadex函数 只能在调用线程中终止自己。