|
《Windows游戏编程大师技巧》(第二版)第11章(34) 0, // default stack Printer_Thread, // use this thread function (LPVOID)1, // user data sent to thread 0, // creation flags, 0=start now. &thread_id); // send id back in this var // now enter into printing loop, make sure // this is shorter than the thread, // so thread finishes last for (int index=0; index<25; index++) { printf("2 "); Sleep(100); } // end for index // note that this print statement may get // interspliced with the output of the // thread, very key! printf("\nWaiting for thread to terminate\n"); // at this point the secondary thread so still be working, // now we will wait for it WaitForSingleObject(thread_handle, INFINITE); // at this point the thread should be dead CloseHandle(thread_handle); // end with a blank line printf("\nAll threads terminated.\n"); } // end main 输出示例: Starting threads... 2 1 2 1 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 Waiting for thread to terminate 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 All threads terminated. 这个程序很简单。通常在创建从线程后就进入打印循环。当这些终止时,调用函数WaitForSingleObject()。如果主线程还有其他工作要做,则继续进行。但在本例中,主线程没有其他任务,因而直接进入等待状态。如果你在运行该程序之前运行了SYSMON.EXE,你会看见进入等待状态后CPU的占用率极低,而在忙循环中CPU被占用得相当厉害。
|