VC中創建多個線程的方法

在VC中,無非是創建線程和寫線程函數
一、常規方法:純使用Platform SDKAPI.
1,  創建線程:
#include <windows.h>
在MFC中通常在OnInitDialog()下面創建線程
//定義參數:SerialControl
//------------------變量函數初始化調用區域--------
  CSerialControl * m_SerialControl=new CSerialControl(); 
m_SerialControl->Create(NULL,"aa",WS_CHILD,CRect(0,0,0,0),this,2,NULL); 
  m_SerialControl->InitAllSerialPort();
//------------------------------------------------ 
HANDLE hThread1=CreateThread(NULL,0,DetectCar,(LPVOID)SerialControl,0,NULL);
CloseHandle(hThread1);//此處關閉線程的句柄,但不意味關閉線程,線程在程序退出時關閉
參數說明:
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,//必須爲NULL 
DWORD dwStackSize, //一般爲0 ,表示堆棧與外部大小相同
LPTHREAD_START_ROUTINE lpStartAddress, //線程函數名稱
LPVOID lpParameter, //傳遞給線程函數的參數,如果爲多個,自定義結構體
DWORD dwCreationFlags, //0表示創建線程後立即啓動線程,如果不是立即啓動需要調用ResumeThread函數
LPDWORD lpThreadId);//用來標記該線程的名稱
 
2,  定義線程函數:
//函數的定義
static       DWORD WINAPI DetectCar(LPVOID lpParameter); //一般用靜態函數
//remark:由於線程函數是靜態函數,如果要在函數中用到對象,必須通過
//函數的實現
/***************************************************
*作者:萬田
*時間:2007-13-03
*函數:DetectCar() 說明:檢測線程
****************************************************/
DWORD WINAPI CISSDlg::DetectCar(LPVOID lpParameter)
{
       TRACE("Thread DetectCar is running/r/n");
       CSerialControl* SControl=(CSerialControl*)lpParameter;
       //define:record which road is car
       int Carexit=0;
       while (TRUE)//do this forever
       {
              //get:which road exit car
              Carexit=SControl->m_GroudDetector1.CarExists();
              ***********
       }

方法二:使用MFC全局函數
CWinThread*  AfxBeginThread(( AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );

 

這個需要自定義 pfnThreadProc():UINT MyControllingFunction( LPVOID pParam );
  及傳遞參數類型。。。。如果創建的是掛起線程,使用CWinThread->ResumeThread 執行

方法三:使用MFC全局函數
CWinThread* AfxBeginThread( CRuntimeClass* pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );
這裏需要從CWinThread 類中派生自己的線程類CMyWinThread  ,
CRuntimeClass *rc=RUNTIME_CLASS(CMyWinThread)....利用返回CWinThread 對象的指針就可以對線程進行各種操作。
方法四:使用自己的線程類,並在堆中創建線程對象
class CMyWinThread : public CWinThread{...},要在派生類中實現自己的虛函數 run()....
CMyWinThread *mth = new CMyWinThread()
mth->Create(....)    mth->ResumeThread()

發佈了4 篇原創文章 · 獲贊 10 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章