微软100题(34)生产者消费者模型实现队列

题目:

实现一个队列。
队列的应用场景为:
一个生产者线程将int 类型的数入列,一个消费者线程将int 类型的数出列

 

多线程题目,多线程实现的方法有信号量,临界区,互斥量,事件对象等,其中临界区消耗的资源最少,因为其他都是应用了内核对象,需要进行用户态和内核态的转换。

本题参考http://blog.csdn.net/v_july_v/article/details/6126444中写的示例代码,采用信号量实现

#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);
  //消费 

  cout<<"custom   "<<q.front()<<endl;   q.pop(); 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;   
}


 


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值