关于Windows的进程处理(二)

最简单例程:函数

// Thread.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <process.h>

unsigned WINAPI ThreadFun1(void *arg)
{
	int cnt = *(int*)arg;
	for (int i = 0; i < cnt; i++)
	{
		Sleep(1000);
		printf("The thread is running.\n");
	}
	return 0;
}

int main()
{
	unsigned threadid;
	int param = 5;
	HANDLE h = (HANDLE)_beginthreadex(NULL, 0, ThreadFun1, &param, 0, &threadid);
	if (h == 0)
		printf("Can not create a thread.\n");
	else 
		Sleep(3000);
	printf("End of main.\n");
	return 0;
}

其运行结果为:线程

The thread is running.
The thread is running.
End of main.
The thread is running.

咱们能够看到进程实际上并未执行够5遍就结束了,这是由于main结束了,系统就结束了全部线程的操做。code

这就要求咱们在main结束前等待进程的结束,这就须要使用WaitForSingleObject与WaitForMultipleObjects两个状态函数了。进程

相关文章
相关标签/搜索