多线程应用程序开发之一 基于MFC CWinThread 派生的工作者线程

来源:互联网 发布:淘宝店铺基本设置 编辑:程序博客网 时间:2024/06/06 02:52
  •  MFC提供了多线程应用程序开发的线程类CWinThread。但是直接使用CWindThread有时会很不方便,本文给出了一个示范性的例子:

TestThread.h

 

#if !defined(AFX_TESTTHREAD_H__639F1B57_D843_493A_9D63_0B45CD8269F1__INCLUDED_)
#define AFX_TESTTHREAD_H__639F1B57_D843_493A_9D63_0B45CD8269F1__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// TestThread.h : header file
//

 

/////////////////////////////////////////////////////////////////////////////
// TestThread thread
class CMfcThreadDemoDlg ;
class TestThread : public CWinThread
{
 //DECLARE_DYNCREATE(TestThread)
protected:
   CMfcThreadDemoDlg* m_dlg;    
  
// Attributes
public:
 
// Operations
public:
   void  SetUI(CMfcThreadDemoDlg* dlg);

 
   void  stopThread();  

   TestThread(CMfcThreadDemoDlg* dlg);
   TestThread();
  
   virtual ~TestThread();
// Overrides
 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(TestThread)
 public:
 virtual BOOL InitInstance();
 virtual int  ExitInstance();
 virtual int Run();
 //}}AFX_VIRTUAL

// Implementation
protected:


 // Generated message map functions
 //{{AFX_MSG(TestThread)
  // NOTE - the ClassWizard will add and remove member functions here.
 //}}AFX_MSG

 //DECLARE_MESSAGE_MAP()
private:
 BOOL isKilled();
 BOOL m_bRunning;
};

 

TestThread.cpp

 

#include "stdafx.h"
#include "mfcThreadDemo.h"
#include "TestThread.h"
#include "mfcThreadDemoDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// TestThread

//IMPLEMENT_DYNCREATE(TestThread, CWinThread)


TestThread::TestThread(CMfcThreadDemoDlg* dlg):m_bRunning(FALSE),m_dlg(dlg)
{

}

TestThread::TestThread():m_bRunning(FALSE)
{

}

TestThread::~TestThread()
{
}

BOOL TestThread::InitInstance()
{
 // TODO:  perform and per-thread initialization here
 return TRUE;
}

int TestThread::ExitInstance()
{
 // TODO:  perform any per-thread cleanup here
 return CWinThread::ExitInstance();
}

int TestThread::Run()
{
 int i=0;
    while (isKilled()==FALSE)
    { 
  if (i<10000)
  {
   i++;
            m_dlg->show(i);
   Sleep(50);
  }
  else
  {
   i=0;
  } 
        
    }
    
 return 0;
}


//BEGIN_MESSAGE_MAP(TestThread, CWinThread)
 //{{AFX_MSG_MAP(TestThread)
  // NOTE - the ClassWizard will add and remove mapping macros here.
 //}}AFX_MSG_MAP
//END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// TestThread message handlers

BOOL TestThread::isKilled()
{
 return m_bRunning;
}

void TestThread::stopThread()
{
    m_bRunning=TRUE;
}

void TestThread::SetUI(CMfcThreadDemoDlg *dlg)
{
    m_dlg=dlg;
}

说明:

  1. TestThread    派生自CWinThread.
  2. 由于自己派生后,产生的TestThread的构造函数是私有的,如果想要和普通类一样使用,需要修改为公有类型。
  3. 本示例增加了线程终止的自动终止的条件。
原创粉丝点击