VC线程入门实例

1. 用MFC AppWizzard(exe) 创建一个project;
2. 在ClassView选项卡下,右键单击project的根目录,在弹出菜单中选择”new class”,然后弹出如下的列表框,在Name中填写CMyThread,Base class:选选择CwinThread,点击”OK”.
clip_image002
3. 线程创建完毕.
4. 为线程类和要调用线程类的类中分别添加3个事件信号
public:
HANDLE m_hStop;
HANDLE m_hStopped;
HANDLE m_hExit;
5. 重载线程类的构造函数,创建一个有3个参数的线程类的构造函数为public,如:
CMyThread (HANDLE hStop,HANDLE hStopped,HANDLE hExit);
6. 在要调用此线程类的类中初始化事件信号和线程,如:
m_hStop = CreateEvent(NULL,true,false,NULL);
m_hStopped = CreateEvent(NULL,true,false,NULL);
m_hExit = CreateEvent(NULL,true,false,NULL);
m_pThread = new CTestThread(m_hStop,m_hStopped,m_hExit);
7. 为线程类和要调用线程类的类中分别添加3个事件信号
public:
HANDLE m_hStop;
HANDLE m_hStopped;
HANDLE m_hExit;
8. 重写线程类的虚函数run();如:
int CMyThread::Run()
{
CString str;
for(int n=0;;n++)//一个死循环
{
DWORD dw = WaitForSingleObject(m_hStop,0);//等待停止信号
if(dw==WAIT_OBJECT_0)
break;
str.Format("%d",n);
m_pMainWnd->PostMessage(WM_TEST,(WPARAM)(str.operator LPCTSTR()),0);
Sleep(100);
}
SetEvent(m_hStopped);//付出关闭线程的信号
return CWinThread::Run();
}
9. 在需要调用此线程类的地方,声明线程类的指针,并调用CreateThread()如下所示:
CMyThread* pMyThread = new CMyThread();
pMyThread ->CreateThread();
10. 重写线程类的ExitInstance()函数,发出关闭信号事件,如:
int CTestThread::ExitInstance()
{
SetEvent(m_hExit);
return CWinThread::ExitInstance();
}
11.线程结束

你可能感兴趣的:(C++,职场,休闲)