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

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,常常会到主消息循环是一件十分重要的事情。如果没有这么做,窗口就会停止重回,界面停止响应。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值