打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
算法35(生产者线程和消费者线程)

 

/*
生产者消费者线程演示
一个生产者线程将int类型的数入列,一个消费者线程将int类型的数出列
*/
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <iostream>
#include <queue>
using namespace std;
HANDLE ghSemaphore;   //信号量
const int gMax = 100; //生产(消费)总数
std::queue<int> q;   //生产入队,消费出队
//生产者线程
unsigned int __stdcall producerThread(void* pParam)
{
 int n = 0;
 while(++n <= gMax)
 {
  //生产
  q.push(n);
  cout<<"produce "<<n<<endl;
  ReleaseSemaphore(ghSemaphore, 1, NULL); //增加信号量
  Sleep(300);//生产间隔的时间,可以和消费间隔时间一起调节
 }
 _endthread(); //生产结束
 return 0;
}
//消费者线程
unsigned int __stdcall customerThread(void* pParam)
{
 int n = gMax;
 while(n--)
 {
  WaitForSingleObject(ghSemaphore, 10000);
  //消费
  q.pop();
  cout<<"custom  "<<q.front()<<endl;
  Sleep(500);//消费间隔的时间,可以和生产间隔时间一起调节
 }
 //消费结束
 CloseHandle(ghSemaphore);
 cout<<"working end."<<endl;
 _endthread();
 return 0;
}
void threadWorking()
{
 ghSemaphore = CreateSemaphore(NULL, 0, gMax, NULL); //信号量来维护线程同步
 
 cout<<"working start."<<endl;
 unsigned threadID;
 HANDLE handles[2];
 handles[0] = (HANDLE)_beginthreadex(
                    NULL,
                    0,
                    producerThread,
                    nullptr,
                    0,
                    &threadID);
 handles[1] = (HANDLE)_beginthreadex(
                    NULL,
                    0,
                    customerThread,
                    nullptr,
                    0,
                    &threadID);
 WaitForMultipleObjects(2, handles, TRUE, INFINITE);
}
int main()
{
 threadWorking();
 getchar();
 return 0;
}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
生产者消费者问题
生产者和消费者
C++11 多线程 生产者消费者
VC下线程同步的三种方法
C++多线程编程入门之经典实例
使用libevent进行多线程socket编程demo
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服