我们在网上搜索vc多线程的创建,一般就如前几次转发的文章一样。
但是,在mfc中,这样子感觉似乎有点麻烦。其实我们可以利用线程派生类的方式创建线程。利用CWinThread 进行用户界面线程的创建。
首先,我们在mfc类中添加类thread,基类是CWinThread。这样会自动创建出thread.h,thread.cpp两个文件。内容如下:
/////////////////////////// thread.h /////////////////////////////////////
#pragma once
// thread
class thread : public CWinThread
{
DECLARE_DYNCREATE(thread)
public: //注意,电脑自动生成的是protected
thread(); // 动态创建所使用的受保护的构造函数
virtual ~thread();
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
protected:
DECLARE_MESSAGE_MAP()
};
/////////////////////////// thread.cpp /////////////////////////////////////
// thread.cpp : 实现文件
//
#include "stdafx.h"
#include "multithread copy.h"
#include "thread.h"
// thread
IMPLEMENT_DYNCREATE(thread, CWinThread)
thread::thread()
{
}
thread::~thread()
{
}
BOOL thread::InitInstance()
{
// TODO: 在此执行任意逐线程初始化
return TRUE;
}
int thread::ExitInstance()
{
// TODO: 在此执行任意逐线程清理
return CWinThread::ExitInstance();
}
BEGIN_MESSAGE_MAP(thread, CWinThread)
END_MESSAGE_MAP()
// thread 消息处理程序
}
然后,在要调用的地方 初始化线程
thread* thread1;
thread1=new thread();//申请线程空间
thread1->CreateThread();//创建线程并启用
最后,根据自己的需要,在thread.h中添加需要的消息函数,并在thread.cpp中实现。在主进程中调用即可。
不知道自己总结的是否正确,往大家指正。。。 谢谢。。。