PostThreadMessage例子

工作线程默认是不会有消息队列的,工作线程中调用PeekMessage可以创建属于自己的消息队列。这样能使用在同一进程不同线程间的通讯。 

PostThreadMessage

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

  • 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 as shown here to force the system to create the message queue.

    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE)

  • Set the event, to indicate that the thread is ready to receive posted messages.

同一进程的

// ThreadMessage.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <process.h>
#include <iostream>

using namespace std;

HANDLE g_event = NULL;

#define MSG_PRINT_CALL_TIME		(WM_USER + 1)
#define MSG_END_THREAD		(WM_USER + 2)

unsigned __stdcall SecondThreadFunc( void* pArguments )
{
	MSG msg;
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
	SetEvent(g_event);
	int count = 0;

	memset(&msg, 0, sizeof(MSG));
	while (GetMessage(&msg, NULL, 0, 0))
	{
		switch (msg.message)
		{
		case MSG_PRINT_CALL_TIME:
			cout<<"MSG_PRINT_CALL_TIME: "<<count<<endl;
			count++;
			break;
		case MSG_END_THREAD:
			cout<<"end thread"<<endl;
			_endthreadex(0);
		default:
			cout<<"default"<<endl;
			break;
		}
	}
    return 0;
} 

int main()
{ 
    HANDLE hThread;
    unsigned threadID;

	g_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (NULL == g_event)
	{
		exit(1);
	}
	
    // Create the second thread.
    hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );

	WaitForSingleObject(g_event, INFINITE);
// 	MSG msg;
// 	memset(&msg, 0, sizeof(MSG));
// 	msg.message = MSG_PRINT_CALL_TIME;
	PostThreadMessage(threadID, MSG_PRINT_CALL_TIME, (WPARAM)1, NULL);
	PostThreadMessage(threadID, MSG_PRINT_CALL_TIME, (WPARAM)10, NULL);
	PostThreadMessage(threadID, WM_USER, (WPARAM)10, NULL);
	PostThreadMessage(threadID, MSG_END_THREAD, (WPARAM)10, NULL);
	
    WaitForSingleObject( hThread, INFINITE );

    // Destroy the thread object.
    CloseHandle( hThread );
	CloseHandle(g_event);

	return 0;
}





不同进程的可以使用进程间通讯机制

WM_COPYDATA


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值