zoukankan      html  css  js  c++  java
  • 【100题】第三十四 实现一个队列

    一,题目:

           生产者消费者线程演示  
                      一个生产者线程将int类型的数入列,一个消费者线程将int类型的数出列 

    二,分析:

            

            这一个,为操作系统上的一个经典例子,以下是july给出的解答    

    三,源码:

    #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<<"workingstart."<<endl;   
        unsigned threadID;   
        HANDLE handles[2];   
        handles[0] = (HANDLE)_beginthreadex(    
                       NULL,    
                       0,    
                       producerThread,    
                       NULL,    
                       0,    
                       &threadID);   
        handles[1] = (HANDLE)_beginthreadex(    
                       NULL,    
                       0,    
                       customerThread,    
                       NULL,    
                       0,    
                       &threadID);    
        WaitForMultipleObjects(2, handles, TRUE, INFINITE);   
    }  
     
    int main()   
    {   
        threadWorking();   
        getchar();   
        return 0;   
    }
     


     

  • 相关阅读:
    HDU 1261 字串数(排列组合)
    Codeforces 488C Fight the Monster
    HDU 1237 简单计算器
    POJ 2240 Arbitrage
    POJ 3660 Cow Contest
    POJ 1052 MPI Maelstrom
    POJ 3259 Wormholes
    POJ 3268 Silver Cow Party
    Codesforces 485D Maximum Value
    POJ 2253 Frogger(最短路)
  • 原文地址:https://www.cnblogs.com/secbook/p/2655015.html
Copyright © 2011-2022 走看看