这篇文章讲生产-消费者模式比较详细
http://ifeve.com/producers-and-consumers-mode/
使用VC++ 模式实现如:
//创建信号量
HANDLE h = ::CreateEvent(NULL,FALSE,FALSE,NULL);
//启动线程
AfxBeginThread(product, this, THREAD_PRIORITY_NORMAL, 0, 0);
AfxBeginThread(consum, this, THREAD_PRIORITY, 0, 0);
//
UINT ***::product(void *pParam){
(***)pParam->product();
return 0;
}
//
UNIT ***::consum(void *p){
(***)p->consum();
return 0;
}
//生产者
void product(){
while(1){
//生产 过程
::Sleep(10);//线程沉睡函数,模拟生产过程
setEvent(h);//发送信号到消费端
}
}
//消费者
void consum(){
while(1){
::WatForSingleObject(h,INFINTE);//信号量阻塞,直到接收到信号量
// 消费 - - 消费
}
}
补充年:
//线程退出信号,可以监听是否退出当前线程
int iExitEvent = ::WaitForSingleObject(m_hExitEvent, 0);
if (WAIT_OBJECT_0 == iExitEvent)
{
return FALSE;
}