|
《Windows游戏编程大师技巧》(第二版)第11章(35) 在这里,函数WaitForSingleObject()有一个使用技巧。假如想知道一个线程在调用该函数时的状态,可以通过用NULL调用WaitForSingleObject()函数来实现,源代码如下: //...code DWORD state = WaitForSingleObject(thread_handle, 0); // get the status // test the status if (state==WAIT_OBJECT_0) { // thread is signaled, i.e. terminated } else if (state==WAIT_TIMEOUT) { // thread is still running } //...code 简单之至,这是检测一个特定的线程是否已结束的绝妙方法。结合这一方法使用全局终止消息是一种非常可靠的终止线程的方法。同时该方法是在实时循环中检测某个线程是否已终止,而无须进入等待状态的好方法。 等待多个对象 问题现在几乎都解决了。Wait*()类函数的最后一个函数就是一个用于等待多个对象或线程信号的函数。我们现在试着编写使用该函数的程序。我们所要做的就是创建一个线程数组,然后将该句柄数组与若干参数一起传递给WaitForMultipleObjects()函数。 当该函数返回时,如果一切正常,那么所有的线程应该都已终止。DEMO11_9.CPPEXE与DEMO11_8.CPPEXE相似,只不过它是创建多线程,然后主线程等待所有其他线程终止而已。在这里,不使用全局终止标志,因为你已知道如何实现这一功能。每个从线程运行几个周期后就终止。DEMO11_9.CPP的源代码如下所示: // DEMO11_9.CPP -An example use of // WaitForMultipleObjects(...) // INCLUDES /////////////////////////////////////////////////// #define WIN32_LEAN_AND_MEAN // make sure certain headers // are included correctly #include <windows.h> // include the standard windows stuff #include <windowsx.h> // include the 32 bit stuff #include <conio.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <math.h> #include <io.h> #include <fcntl.h> // DEFINES /////////////////////////////////////////////////// #define MAX_THREADS 3 // PROTOTYPES ///////////////////////////////////////////////// DWORD WINAPI Printer_Thread(LPVOID data); // GLOBALS //////////////////////////////////////////////////// // FUNCTIONS ////////////////////////////////////////////////// DWORD WINAPI Printer_Thread(LPVOID data) { // this thread function simply prints out data 50 // times with a slight delay for (int index=0; index<50; index++) { printf("%d ",(int)data+1); // output a single character
|