这是我现在使用的一种线程通信方式的代码片段,两个线程之间通过自定义消息进行通知,
#define MY_MSG WM_USER+100 //线程通信的自定义消息
//消费者
DWORD Consumer::Run()
{//创建线程并启动
DWORD ThreadId;
m_hThread = CreateThread( NULL,0,Routine,0,0,&ThreadId );//创建更新线程
if( NULL == m_hThread )
{
return -1;//启动失败
}
return ThreadId;//线程启动成功
}
DWORD WINAPI Consumer::Routine( LPVOID lParam)
{//线程运行函数
std::cout<<"消费者线程启动\n";
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
while(true)
{
if(GetMessage(&msg,0,0,0)) //get msg from message queue
{
switch(msg.message)
{
case MY_MSG:
//do something here
std::cout<<"收到消息"<<std::endl;
break;
}
}
};
return 0;
}
//生产者
DWORD Producer::Run(LPDEALFUNCTION dealfun,LPVOID lParam)
{
DWORD ThreadId;
m_DealFun = dealfun;
m_DealFunParam = NULL;
m_hThread = CreateThread( NULL,0,Routine,this,0,&ThreadId );//创建监控线程
if( NULL == m_hThread )
{
return -1;
}
return ThreadId;
}
DWORD WINAPI Producer::Routine( LPVOID lParam )
{
Producer& obj = *(Producer*)lParam;//生产者对象
while( !obj.m_bRequestStop )
{//线程就不断运行直到收到用户的退出请求
obj.m_DealFun(obj.m_DealFunParam );
}
return 0;
}
//main.cpp
HANDLE hStartEvent; // thread start event
unsigned nConsumerID,nProducerID;
void __stdcall MyDeal( LPVOID lParam )
{
std::cout<<"开始发送消息.."<<std::endl;
if(!PostThreadMessage(nConsumerID,MY_MSG,NULL,NULL))//post thread msg
{
printf("post message failed,errno:%d\n",::GetLastError());
}
::Sleep(1000);
}
int main()
{
Consumer consumer;
nConsumerID = consumer.Run();//启动更新线程
if(nConsumerID == -1)
{
std::cout<<"start thread failed"<<std::endl;
return -1;
}
Producer pProducer;
nProducerID = pProducer.Run(&MyDeal, 0 );//启动监控线程
if( nProducerID==-1 )
return -1;
return 0;
}