Win32下的线程和MFC的线程实现


Win32线程

1.首先在.h文件中声明线程句柄和线程ID

    HANDLE                   hThread;   //线程句柄
    DWORD                     ThreadID;  //线程ID


 线程函数的声明

   void           ThreadFunc();     //MultiThread1Dlg 线程函数的声明,应该在**Dlg类的外部


2.在.cpp文件中合适的位置(需要线程运行的位置)调用CreateThread函数

hThread=CreateThread(NULL,
                         0,
                          (LPTHREAD_START_ROUTINE)ThreadFunc,
                          NULL,
                         0,
                         &ThreadID);
    GetDlgItem(ID_BN_START)->EnableWindow(FALSE);
    GetDlgItem(ID_BN_STOP)->EnableWindow(TRUE);




PS:

MSDN中CreateThread原型:

HANDLE CreateThread(
 LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
  SIZE_T dwStackSize, // initial stack size
 LPTHREAD_START_ROUTINE lpStartAddress, // thread function
  LPVOID lpParameter, // thread argument
  DWORD dwCreationFlags, // creation option
  LPDWORD lpThreadId // thread identifier
);


返回值:
函数成功,返回线程句柄;函数失败返回false。
若不想返回线程ID,设置值为NULL。
函数说明:
创建一个线程。
语法:
hThread = CreateThread (&security_attributes, dwStackSize, ThreadProc,pParam, dwFlags, &idThread) ;
一般并不推荐使用 CreateThread函数,而推荐使用RTL库里的System单元中定义的 BeginThread函数,因为这除了能创建一个线程和一个入口函数以外,还增加了几项保护措施。
在MFC程序中,应该调用AfxBeginThread函数,在Visual C++程序中应调用_beginthreadex函数。

MFC线程:
1.继承CWinThread
.h文件
class MyThread1 : public CWinThread
{
    DECLARE_DYNCREATE(MyThread1)
    
private:
    
protected:
    DECLARE_MESSAGE_MAP()

public:
    //static tRunParam*    m_pCfgPm;                //配置参数
    static void*        m_pFrameWnd;            //扫描主窗口

    MyThread1();           // 动态创建所使用的受保护的构造函数
    virtual ~MyThread1();
    virtual BOOL InitInstance();
    virtual int ExitInstance();
    virtual int Run();
};

2.在.cpp文件中
IMPLEMENT_DYNCREATE(MyThread1, CWinThread)

MyThread1::MyThread1()
{
    ///////////////////////////
    m_bAutoDelete = true;
}

MyThread1::~MyThread1()
{
    pUserApi->Release();
}

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

BOOL MyThread1::InitInstance(void)
{

    return TRUE;
}

int MyThread1::ExitInstance(void)
{

    return CWinThread::ExitInstance();
}

int MyThread1::Run()
{
    
    //::AfxMessageBox("搞定!");

    //CString strT;strT.Format("%s %s %s %s",FRONT_ADDR,BROKER_ID,INVESTOR_ID,PASSWORD);::AfxMessageBox(strT);


    // 初始化UserApi
    pUserApi = CThostFtdcMdApi::CreateFtdcMdApi();                    // 创建UserApi
    pUserSpi = new CMdSpi();
   

    //::AfxMessageBox("01");

    pUserApi->RegisterSpi((CThostFtdcMdSpi*)pUserSpi);                                // 注册事件类
    pUserApi->RegisterFront(HQ_FRONT_ADDR);                            // connect
    pUserApi->Init();
    pUserApi->Join();

    //::AfxMessageBox("02");

    return 0;
}


你可能感兴趣的:(thread,线程,Win32,继承)