一、多线程杂记
1、计算问题的类型。
决定给定的多线程计算是否是一个优秀的方案最重要的因素是该计算是一个基于CPU的计算还是一个基于IO的计算。
2、多线程的设计目标
a、增强的性能 b、增强的容量(也称响应,指每一个计算的平均处理周期的时间) c、快速的反应
二、利用Win 32 API的线程编程技术
1、编写线程函数
DWORD WINAPI YourThreadFunc(LPVOID lpvThreadParm)
2、创建一个线程
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, // pointer to security attributes
DWORD dwStackSize, // initial thread stack size
LPTHREAD_START_ROUTINE lpStartAddress, // pointer to thread function
LPVOID lpParameter, // argument for new thread
DWORD dwCreationFlags, // creation flags
LPDWORD lpThreadId // pointer to receive thread ID
);
3、终止线程
VOID ExitThread(
DWORD dwExitCode // exit code for this thread
);
或
BOOL TerminateThread(
HANDLE hThread, // handle to the thread
DWORD dwExitCode // exit code for the thread
);
4、设定线程的优先级
BOOL SetThreadPriority(
HANDLE hThread, // handle to the thread
int nPriority // thread priority level
);
5、挂起和恢复线程
恢复
DWORD ResumeThread(
HANDLE hThread // identifies thread to restart
);
挂起
DWORD SuspendThread(
HANDLE hThread // handle to the thread
);
注:一个线程可以被挂起多次,在系统为其分配CPU之前,被恢复的次数一定要等于被挂起的次数。
三、利用MFC进行多线程编程
基本原理同Win 32函数一致
在MFC中,有两种线程 A、用户界面线程 B、工作线程
用户界面线程:常用于接收用户的输入,处理相应的事件和消息。在用户界面线程中,包含一个消息处理循环,如从CWiThread类派生出的CWinApp
工作线程:常用于任务处理(如计算)。不要求用户输入,对用而言,它在后台运行。
在编写用户界面线程时,需要从CWinThread派生出自己的线程类
步骤:
(1)用ClassWizerd派生一个新的类,基类是CWinThread
注:类的DECLEARE_DYNCREATE 和 IMPLEMENT_DYNCREATE宏是必需的。因为创建线程时需要动态创建类的对象
(2)创建并启动线程