|
《Windows游戏编程大师技巧》(第二版)第11章(24) thread_handle = CreateThread(NULL, // default security 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 takes longer than thread, // so thread finishes first for (int index=0; index<50; index++) { printf("2 "); Sleep(100); } // end for index // 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 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 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 All threads terminated. 正如你所看到的输出结果,每一个线程只运行很短的一段时间,然后系统便切换至另一个正等待运行的线程。在这种情况下,操作系统只是简单地在主线程和从线程间来回切换。 现在让我们试着创建一个多线程程序。你只需对DEMO11_5.CPP略加修改便可实现该功能。你只需多次调用CreateThread()函数,每次调用就创建一个线程。而且每次传递给所创建线程的数据将被打印出来,这样便可以区分你所创建的线程。 DEMO11_6.CPPEXE包含了修改后的多线程程序,我在下面列出供你参考。注意在这里我用数组储存线程句柄和ID。
|