多线程中使用WaitForSingleObject结束线程,啥也不说,先上代码
#include
#include
#include
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 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
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。