使用Windows API PostThreadMessage進行線程間消息通信


使用Windows API PostThreadMessage進行線程間消息通信

相信好多人都聽過這個Windows APIPostThreadMessage,今天終於有時間來詳細的研究一下,據我所知好多的公司在面試的時候都會提到這個API,因為常寫代碼的人一定會知道這個API,通過這個提問,可以考察一個人對細節的掌握程度。不多說了,開始正題。

如下函數原型From MSDN:

BOOL WINAPI PostThreadMessage(_In_ DWORD idThread,_In_ UINT Msg,_In_ WPARAM wParam,_In_ LPARAM lParam);

idThread -      [in] Type: DWORD The identifier of the thread to which the message is to be posted.

Msg     -       [in] Type: UINT The type of message to be posted.

wParam -        [in] Type: WPARAM Additional message-specific information.

lParam -        [in] Type: LPARAM Additional message-specific information.

也就是說為了使用這個API我們只要提供接受線程的線程ID以及相應的參數就行了,如下是代碼實現,首先創建worker thread 並且在worker thread中創建消息循環,這樣當我們在主線程中PostThreadMessage的時候worker thread就可以對進來的消息進行處理了,我們可以給worker thread發送TALK_MESSAGEWM_QUIT message, 一旦worker thread收到WM_QUIT message, worker thread將報告給主線程自己要退出了,然后結束自己的生命周期。

DWORD ThreadProc(LPVOID lParam)

{

        MSG msg;

        while(GetMessage(&msg,0,0,0))

        {

                if(msg.message == TALK_MESSAGE)

                {

                        MessageBox(NULL,L"Hi",L"Worker Thread",MB_OK);

                }

                DispatchMessage(&msg);

        }

        MessageBox(NULL,L"Thread will close by pressing OK",L"From Worker Thread",MB_OK);

        AfxGetApp()->m_pMainWnd->PostMessageW(TALK_MESSAGE+1,0,0);

        return 0;

}

void CPostThreadMSGDlg::OnBnClickedOk()

{

        CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc,0,0,&m_dwThread);

        ::MessageBox(NULL,L"Worker Thread Created!",L"From main Thread",MB_OK);

        OnOK();

}

void CPostThreadMSGDlg::OnBnClickedButtonHi()

{

        PostThreadMessage(m_dwThread,TALK_MESSAGE,0,0);

}

void CPostThreadMSGDlg::OnBnClickedButtonCllose()

{

        PostThreadMessage(m_dwThread,WM_QUIT,0,0);

}

LONG CPostThreadMSGDlg::OnWorkerThreadQuitFunction(WPARAM wParam, LPARAM lParam)

{      

        ::MessageBox(NULL,L"Main thread have known Worker Thread died!",L"From main Thread",MB_OK);

        return 0;

}

總結

本文詳細解釋了使用Windows API PostThreadMessage進行線程間消息通信的過程,給出了示例代碼,並且對示例代碼的運行原理進行的說明,相信通過本文的介紹大家會對這個API有深刻的印象。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM