您的位置:首页 > 其它

关于Windows的进程处理(二)

2017-07-13 00:00 183 查看
最简单例程:

// 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, ¶m, 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结束了,系统就结束了所有线程的操作。

这就要求我们在main结束前等待进程的结束,这就需要使用WaitForSingleObject与WaitForMultipleObjects两个状态函数了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C 线程