MFC多執行緒程式設計實踐總結之AfxBeginThread()
阿新 • • 發佈:2018-11-06
在MFC多執行緒程式設計中,執行緒函式呼叫類內成員變數和成員函式的步驟:
1.將執行緒函式在類.h檔案中類內宣告,並用修飾符static修飾;
class CtestDlg : public CDialogEx
{
public:
...
static UINT ThreadFunc(LPVOID pParam); //執行緒函式宣告,類內定義需使用static進行修飾,若無static修飾則需在類外定義。
void process(); //類的成員函式,process()函式中需要用到類的其他成員變數
...
};
2.在類.cpp檔案中定義執行緒函式
//執行緒函式
UINT CtestDlg::ThreadFunc(LPVOID pParam)
{
CtestDlg *dlg = (CtestDlg*)pParam;
dlg->process();
return 0;
}
3.在按鈕點選事件響應函式中定義按鈕點選響應函式
//按鈕響應事件
void CtestDlg::OnBnClickedTest()
{
CWinThread *pThread = (CWinThread*)AfxBeginThread(ThreadFunc, this); //傳入this指標作為執行緒函式的引數,啟動執行緒
}