前言
對於寫mfc介面來說,如果某個訊息對映函式流程執行時間太長,有太多的sleep()和 while(1)會導致執行緒時間過長,mfc介面卡死,因此需要學會用多執行緒
思路
1. 建立流程
2. 建立執行緒呼叫的函式
3. 結束執行緒
第一步:建立執行緒
cwinthread *m_pthread;m_pthread=nullptr;
m_pthread=afxbeginthread(loadnlpdict,this);//loadnlpdict是呼叫的函式
第二步:執行緒呼叫的函式:
此函式必須是個靜態或者是不屬於該類的函式
uint loadnlpdict(lpvoid lpparam);
關於建立執行緒:
cwinthread *mythread = afxbeginthread(myfunction,pparam,thread_priority_normal,0,0,null);//mythread是定義的執行緒指標
//myfunction是呼叫函式
//pparam呼叫函式內lpvoid引數,作為傳執行緒引數
//thread_priority_normal是執行緒優先順序,一般置0,和主線程一致
//第乙個0代表和主線程一樣的棧
//第二個0代表建立執行緒後就開始執行
//null和主線程一樣安全
現成的等待,掛起與喚醒
mythread->suspendthread();//讓執行緒等待!mythread->resumethread();//喚醒暫停的執行緒!
檢視執行緒狀態
dword code;getexitcodethread(mythread->m_hthread,&code);
if(code==still_active)
else
結束執行緒(強行結束)
terminatethread(mythread->m_hthread,0);
注意:執行緒函式可以放在cpp檔案內
前加static變成全域性函式(不一定放在c*****cpp中)
執行緒指標要放在介面類的protect中
cwinthread *mythread;
但執行緒函式可以單獨拿出來
在標頭檔案中宣告
unit tetthread(lpvoid pparam)
在cpp檔案內定義(不加static)
建立執行緒最好用:
afxbeginthread(tetthread,this);
這樣執行緒函式中pparam可以不為空指標
MFC多執行緒程式設計總結
mfc多執行緒程式設計總結 mfc中,在多個執行緒之間通話 資料共享與同步的方法有 1.全域性變數。全域性變數需要用volatile宣告以防止使用暫存器導致出錯。也可以使用interlockedincrement在阻塞其它執行緒的條件下修改單個全域性變數。這是一種簡單的在同一程序中線程之間通話與資料...
MFC多執行緒程式設計總結
在mfc程式中使用afxbeginthread函式來建立乙個執行緒,該函式因引數不同而具有兩種過載函式,分別對應工作者執行緒和使用者介面 ui 執行緒。一 工作執行緒 1 建立執行緒mfc api函式 cwinthread afxbeginthread afx threadproc pfnthrea...
MFC中多執行緒問題
mfc中多執行緒問題 問題是這樣的 我們程式設計涉及到乙個多執行緒問題,當把執行緒函式定義為全域性時正常,而定義為類的成員函式時就會出錯。說錯誤是afxbeginthread不能從unsinged int void 轉換為第乙個引數。我在google上搜尋了一下,找到了幾個解決方案。cpp 1.cl...