您的位置:首页 > 其它

如何建立多线程之间的消息通信

2008-09-26 15:13 381 查看
开发服务器程序经常要涉及到多线程之间进行消息通信,比如子线程要通知父线程要退出,或一些其他的信息.

因为服务器的多线城都是工作线程,是没有CWnd,所以如果要接收消息,必须自己建立消息队列来获取消息,同时

要建立消息映射.

具体如下:

在.h文件中加入DECLARE_MESSAGE_MAP()

在.cpp文件中加入

BEGIN_MESSAGE_MAP(CServiceSrvApp, CWinApp)
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
ON_THREAD_MESSAGE(WM_THREADMSG_WORKSOCKET_EXIT,ThreadMsgFunction)
END_MESSAGE_MAP()

强制建立消息通道的代码如下:

if(PeekMessage(&Msg , NULL, 0, 0, PM_REMOVE))
{
PreTranslateMessage(&Msg);
DispatchMessage(&Msg);
TranslateMessage(&Msg);
}

实现发送消息的函数如下:
_AFXWIN_INLINE BOOL CWinThread::PostThreadMessage(UINT message, WPARAM wParam, LPARAM lParam)
{ ASSERT(m_hThread != NULL); return ::PostThreadMessage(m_nThreadID, message, wParam, lParam); }

以下是MSDN中对PostThreadMessage的描述:

PostThreadMessage

The PostThreadMessage function places (posts) a message in the message queue of the specified thread and then returns without waiting for the thread to process the message.
BOOL PostThreadMessage(
DWORD idThread, // thread identifier
  UINT Msg,       // message to post
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

Parameters

idThread
Thread identifier of the thread to which the message will be posted.
The function fails if the specified thread does not have a message queue. The system creates a thread's message queue when the thread makes its first call to one of the Win32 USER or GDI functions. For more information, see the Remarks section.

Msg
Specifies the type of message to be posted.
wParam
Specifies additional message-specific information.
lParam
Specifies additional message-specific information.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError. GetLastError returns ERROR_INVALID_THREAD_ID if idThread is not a valid thread identifier, or if the thread specified by idThread does not have a message queue.

Remarks

The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use one of the following methods to handle this situation:

Call PostThreadMessage. If it fails, call the Sleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds.
Create an event object, then create the thread. Use the WaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage. In the thread to which the message will be posted, call PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE) to force the system to create the message queue. Set the event, to indicate that the thread is ready to receive posted messages.

The thread to which the message is posted retrieves the message by calling the GetMessage or PeekMessage function. The hwnd member of the returned MSG structure is NULL
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: