1. 程式人生 > >再談執行緒等待函式WaitForSingleObject和CloseHandle

再談執行緒等待函式WaitForSingleObject和CloseHandle

多執行緒中使用WaitForSingleObject結束執行緒,啥也不說,先上程式碼

#include <windows.h>
#include <String.h>
#include <stdio.h>

int Fun1Proc( void )
{
	int i;
	char *c = "thread one " ; 
	for(i = 0; i < 100; i++)
	{
		printf("%s number: %d \n",c ,i+1 );
	}	
	return 0;
}


int main(  )
{
	HANDLE hThread1;
	hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	int i;
	char *c = "main thread " ; 
	for(i = 0; i < 100; i++)
	{
		printf("%s number: %d \n",c ,i+1 );
	}
	CloseHandle(hThread1);

	return 0;
}
執行結果:

main thread 1
main thread 2
main thread 3
...

main thread 98
main thread 99
main thread 100

為什麼執行緒函式沒有執行呢?奇怪,多執行幾遍,發現每次結果不一定相同,下面是另一次執行結果:

main thread 1
main thread 2
main thread 3

...

main thread 71

thread one 1
thread one 2

main thread 72

main thread 73

...

thread one 3
thread one 4

main thread 75

main thread 76


...

main thread 98
main thread 99
main thread 100

可見,主函式執行完了,整個程式就退出了,不會等到Fun1Proc()執行完再退出。等2秒會不會好一點呢?下面是修改後的main程式

int main(  )
{
	HANDLE hThread1;
	hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	Sleep(2000);

	int i;
	char *c = "main thread " ; 
	for(i = 0; i < 100; i++)
	{
		printf("%s number: %d \n",c ,i+1 );
	}
	

	return 0;
}


執行結果:
thread one 1
thread one 2
thread one 3

...

thread one 98
thread one 99
thread one 100

main thread 1
main thread 2
main thread 3
...

main thread 98
main thread 99
main thread 100

這下貌似可以,但這個2秒只是估算的一個時間,並不準確,有的執行緒執行時間很長的,程式碼還要再修改下:
int main(  )
{
	HANDLE hThread1;
	hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	WaitForSingleObject(hThread1, INFINITE);

	int i;
	char *c = "main thread " ; 
	for(i = 0; i < 100; i++)
	{
		printf("%s number: %d \n",c ,i+1 );
	}
	CloseHandle(hThread1);

	return 0;
}
這下好了,每次執行結果都正確,WaitForSingleObject的作用就是等待執行緒自動結束,繼續執行後面的程式。這個CloseHandle為什麼這麼靠後呢?把它放前面一點好不好?不是說每次建立執行緒以後直接CloseHandle更好嗎?好,那就挪到上面試試
int main(  )
{
	HANDLE hThread1;
	hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	CloseHandle(hThread1);
	WaitForSingleObject(hThread1, INFINITE);

	int i;
	char *c = "main thread " ; 
	for(i = 0; i < 100; i++)
	{
		printf("%s number: %d \n",c ,i+1 );
	}
	

	return 0;
}

執行後發現,又和一開始一樣了,main thread 中穿插著 thread one。 原來是CloseHandle之後,WaitForSingleObject得不到thread的控制代碼,沒法再等到這個thread結束,呵呵。所以,如果後面還要用到這個thread控制代碼,就不要closeHandle;如果用不到,就可以先closeHandle。