PeekMessage、WaitForSingleObject、PostThreadMessage多线程使用示例
2012-04-23 08:50
489 查看
#include <windows.h> #include <cstdio> #include <process.h> #define MY_MSG WM_USER+100 const int MAX_INFO_SIZE = 20; HANDLE hStartEvent; // thread start event // thread function unsigned __stdcall fun(void *param) { printf("thread fun start\n"); MSG msg; PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); if(!SetEvent(hStartEvent)) //set thread start event { printf("set start event failed,errno:%d/n",::GetLastError()); return 1; } printf("新线程已经启动正等待接收数据\r\n"); while(true) { if(GetMessage(&msg,0,0,0)) //get msg from message queue { switch(msg.message) { case MY_MSG: char * pInfo = (char *)msg.wParam; printf("recv %s\r\n",pInfo); delete[] pInfo; break; } } }; return 0; } int main() { HANDLE hThread,hThread1; unsigned nThreadID,nThreadID1; hStartEvent = ::CreateEvent(0,FALSE,FALSE,0); //create thread start event if(hStartEvent == 0) { printf("create start event failed,errno:%d\r\n",::GetLastError()); return 1; } //start thread hThread = (HANDLE)_beginthreadex( NULL, 0, &fun, NULL, 0, &nThreadID ); if(hThread == 0) { printf("start thread failed,errno:%d/n",::GetLastError()); CloseHandle(hStartEvent); return 1; } printf("启动了新线程\r\n"); //wait thread start event to avoid PostThreadMessage return errno:1444 ::WaitForSingleObject(hStartEvent,INFINITE); CloseHandle(hStartEvent); ::Sleep(1000); int count = 0; while(true) { char* pInfo = new char[MAX_INFO_SIZE]; //create dynamic msg sprintf(pInfo,"msg_%d",++count); if(!PostThreadMessage(nThreadID,MY_MSG,(WPARAM)pInfo,0))//post thread msg { printf("post message failed,errno:%d\r\n",::GetLastError()); delete[] pInfo; } ::Sleep(1000); } CloseHandle(hThread); return 0; }
相关文章推荐
- c++ 线程中CreateEvent SetEvent/ResetEvent WaitForSingleObject的使用
- 【C++】WaitForSingleObject函数的使用&&WaitForSingleObject和CEvent用法
- 线程中CreateEvent和SetEvent及WaitForSingleObject的用法-------wince里面的中断IST经常使用。
- MFC主线程使用WaitForSingleObject阻塞的问题 http://blog.csdn.net/sysprogram/article/details/17383455
- 程序退出时使用WaitForSingleObject导致程序阻塞的原因及解决方法
- WaitForSingleObject和WaitForMultipleObjects使用详解
- 在界面线程不能使用Sleep和WaitForSingleObject之类的函数, 使用 MsgWaitForMultipleObjects
- 线程中CreateEvent和SetEvent及WaitForSingleObject的用法-------wince里面的中断IST经常使用
- CreateMutex WaitForSingleObject ReleaseMutex使用
- 转载:CreateMutex WaitForSingleObject ReleaseMutex使用
- 多线程访问文件问题中WaitForSingleObject方法的使用,及其效率!
- WaitForSingleObject和WaitForMultipleObjects使用详解
- 关于 CreateEvent 和WaitForMultipleObjects以及 WaitForSingleObject 等函数的使用实例
- 关于WaitForSingleObject的使用
- WaitForSingleObject和WaitForMultipleObjects使用详解
- WaitForSingleObject和CEvent的结合使用
- WaitForSingleObject使用详解
- WaitForSingleObject实际使用中犯的错
- 主线程使用WaitForSingleObject和MsgWaitForMultipleObjects等待线程返回值
- WaitForSingleObject和WaitForMultipleObjects使用详解