您的位置:首页 > 其它

《Win32多线程程序设计》读书笔记(一)

2013-09-05 23:54 429 查看
1,可以使用GetExitThreadCode函数获取线程函数结束时的返回值

2,多线程程序设计成功的关键:

2.1,各线程的数据要分离开来,避免使用全局变量
2.2,不要在线程之间共享GDI对象
2.3,确定你知道你的线程状态。不要径自结束程序而不等待他们的结束
2.4,让主线程处理用户界面(UI)


3,不要使用busy loop,它对严重影响系统效率。所谓的busy loop类似以下代码

DWORD exitCode;
do
{
printf("child thread is still busy...\n");
GetExitCodeThread(hThrd, &exitCode);
}while(exitCode == STILL_ACTIVE);
4,可以使用性能监视器查看CPU使用情况,当使用busy loop等待线程结束时,cpu使用率会大大提高

5,等待一个线程结束时应使用WaitForSingleObject,这个函数等待时只消耗很少的cpu,msdn注释:

The WaitForSingleObject function checks the current state of the specified object. If the object's state is nonsignaled, the calling thread enters an efficient wait state. The thread consumes very little processor time while waiting for
the object state to become signaled or the time-out interval to elapse.

6,可以使用WaitForMultipleObjectsEx等待多个线程的结束

7,可以使用MsgWaitForMultipleObjects同时等待内核对象和消息(这个可以修改GUI线程的主消息循环),具体使用参见本书第3章

8,Windows程序的主消息循环

while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

其中GetMessage函数只有在消息队列中存在消息时才返回,但它只会消耗很少的cpu,因为当消息队列中没有消息时,等待线程进入睡眠状态。

这个函数是Win32“合作性多任务”的关键

9,常常会到主消息循环是一件十分重要的事情。如果没有这么做,窗口就会停止重回,界面停止响应。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程