VC++线程通信

 

这是我现在使用的一种线程通信方式的代码片段,两个线程之间通过自定义消息进行通知 ,


#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 ;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值