小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

算法35(生產(chǎn)者線程和消費者線程)

 白雪~~~ 2012-03-20

 

/*
生產(chǎn)者消費者線程演示
一個生產(chǎn)者線程將int類型的數(shù)入列,一個消費者線程將int類型的數(shù)出列
*/
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <iostream>
#include <queue>
using namespace std;
HANDLE ghSemaphore;   //信號量
const int gMax = 100; //生產(chǎn)(消費)總數(shù)
std::queue<int> q;   //生產(chǎn)入隊,消費出隊
//生產(chǎn)者線程
unsigned int __stdcall producerThread(void* pParam)
{
 int n = 0;
 while(++n <= gMax)
 {
  //生產(chǎn)
  q.push(n);
  cout<<"produce "<<n<<endl;
  ReleaseSemaphore(ghSemaphore, 1, NULL); //增加信號量
  Sleep(300);//生產(chǎn)間隔的時間,可以和消費間隔時間一起調(diào)節(jié)
 }
 _endthread(); //生產(chǎn)結(jié)束
 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);//消費間隔的時間,可以和生產(chǎn)間隔時間一起調(diào)節(jié)
 }
 //消費結(jié)束
 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;
}

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多