利用信号量解决生产者消费者问题 第5页
std::cerr << "Succeed" << std::endl;
}
//输出缓冲区当前的状态
for (int i=0;i<SIZE_OF_BUFFER;++i)
{
std::cout << i <<": " << g_buffer[i];
if (i==in)
std::cout << " <-- 生产";
if (i==out)
std::cout << " <-- 消费";
std::cout << std::endl;
}
}
//消耗一个产品
void Consume()
{
std::cerr << "Consuming " << ConsumeID << " *** ";
std::cerr << "Succeed" << std::endl;
}
5.3生产者和消费者算法
//生产者
DWORD WINAPI Producer(LPVOID lpPara)
{
while(g_continue)
{
WaitForSingleObject(g_hFullSemaphore,INFINITE);
WaitForSingleObject(g_hMutex,INFINITE);
Produce();
Append();
Sleep(1500);
ReleaseMutex(g_hMutex);
ReleaseSemaphore(g_hEmptySemaphore,1,NULL);
}
return 0;
}
//消费者
DWORD WINAPI Consumer(LPVOID lpPara)
{
while(g_continue)
{
WaitForSingleObject(g_hEmptySemaphore,INFINITE);
WaitForSingleObject(g_hMutex,INFINITE);
Take();
Consume();
Sleep(1500);
ReleaseMutex(g_hMutex);
ReleaseSemaphore(g_hFullSemaphore,1,NULL);
}
return 0;
}
上一页 [1] [2] [3] [4] [5] [6] 下一页