關於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兩個狀態函數了。進程

相關文章
相關標籤/搜索