使用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有深刻的印象。

 

转载于:https://www.cnblogs.com/pugang/archive/2012/08/24/2654278.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值