在多线程下面,有时候会但愿等待某一线程完成了再继续作其余事情,要实现这个目的,可使用Windows API函数WaitForSingleObject,或者WaitForMultipleObjects。这两个函数都会等待Object被标为有信号(signaled)时才返回的。
那么,什么是信号呢?简单来讲,Windows下建立的Object都会被赋予一个状态量。若是Object被激活了,或者正在使用,那么该Object就是无信号,也就是不可用;另外一方面,若是Object可用了,那么它就恢复有信号了。这两个函数的优势是它们在等待的过程当中会进入一个很是高效沉睡状态,只占用极少的CPU时间片。多线程
DWORD WINAPI WaitForSingleObject( _In_ HANDLE hHandle, _In_ DWORD dwMilliseconds );
DWORD WINAPI WaitForMultipleObjects( _In_ DWORD nCount, _In_ const HANDLE *lpHandles, _In_ BOOL bWaitAll, _In_ DWORD dwMilliseconds );
若是该内核对象处于已通知状态,则该函数当即返回WAIT_OBJECT_0。
若是等待超时,该函数返回WAIT_TIMEOUT。
若是该函数失败,返回WAIT_FAILED。函数
咱们能够根据返回值来判断进程的当前状态,来决定main函数是否退出。线程
#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"); return 0; } DWORD st = WaitForSingleObject(h, INFINITE); if (st == WAIT_FAILED) printf("Failed to wait a thread.\n"); if (st == WAIT_OBJECT_0) printf("The thread is stoped.\n"); if (st == WAIT_TIMEOUT) printf("Timeout to wait a thread.\n"); printf("End of main.\n"); return 0; }
其运行结果以下:code
The thread is running. The thread is running. The thread is running. The thread is running. The thread is running. The thread is stoped. End of main.
这代表main程序等待进程结束后才退出的。对象
但咱们若是将wait函数中的超时设置减小,例如将INFINITE调整为5000后,则结果以下:进程
DWORD st = WaitForSingleObject(h, 5000);
The thread is running. The thread is running. The thread is running. The thread is running. Timeout to wait a thread. End of main.
这就会形成等待进程超时退出一样也会形成进程的结束。也就是说在短期内运行的进程能够经过WaitForSingleObject或WaitForMultipleObjects函数来处理,但若是是长时间的进程则有问题了。ip
简单处理办法是使用循环等待方法,代码修改以下:it
DWORD st; do { printf("Wait a time ...\n"); st = WaitForSingleObject(h, 3000); } while (st == WAIT_TIMEOUT);
其运行结果为:class
Wait a time ... The thread is running. The thread is running. The thread is running. Wait a time ... The thread is running. The thread is running. End of main.
从结果上看,这种循环等待是有效果的。thread