Windows API PostThreadMessage进行线程间消息通信
来源:互联网 发布:动态规划算法 编辑:程序博客网 时间:2024/06/05 22:50
相信好多人都听过这个Windows API:PostThreadMessage,今天终于有时间来详细的研究一下,据我所知好多的公司在面试的时候都会提到这个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_MESSAGE,WM_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进行线程间消息通信
- 使用Windows API PostThreadMessage进行线程间消息通信
- 使用Windows API PostThreadMessage进行线程间消息 http://www.cnblogs.com/pugang/archive/2012/08/24/2654278.html
- PostThreadMessage实现多线程间消息通信
- PostThreadMessage window线程间传送消息
- PostThreadMessage 线程的消息
- 线程通信-PostThreadMessage
- Windows 线程间消息通信
- 向线程投递消息PostThreadMessage
- 使用PostThreadMessage在Win32线程间传递消息
- 使用PostThreadMessage在Win32线程间传递消息
- 使用PostThreadMessage在Win32线程间传递消息
- 使用PostThreadMessage在Win32线程间传递消息
- 使用PostThreadMessage在Win32线程间传递消息 (zhuan)
- 使用PostThreadMessage在Win32线程间传递消息
- 使用PostThreadMessage在Win32线程间传递消息
- 使用PostThreadMessage在Win32线程间传递消息
- [转贴]使用PostThreadMessage在Win32线程间传递消息
- 工作中的要点记录
- Hibernate 拦截器Interceptor使用
- NSArray按字母顺序排序
- 数据分析-数据准备
- 解决Eclipse中启动genymotion模拟器出错的问题
- Windows API PostThreadMessage进行线程间消息通信
- android如何实现按钮的点击水波纹效果:
- 多线程CreateThread函数的用法及注意事项
- Action以及Func使用
- 'XXX ' was compiled with optimization
- php数据库访问变慢的一个原因
- 解析XML:DOM、SAX、PULL
- 【iOS 开发】基本 UI 控件详解 (UIButton | UITextField | UITextView | UISwitch)
- jQuery提示插件alertify使用指南