訊號量實現生產者消費者問題
阿新 • • 發佈:2019-02-05
#include "stdafx.h" #include <iostream> #include <stdio.h> #include <windows.h> #include <deque> #include <conio.h> HANDLE Empty,full,mutex; int x=0; int y=0; std::deque<int> queue_; void output() { for (std::deque<int>::iterator it=queue_.begin(); it!=queue_.end(); ++it) { std::cout << *it; std::cout << ""; } std::cout<<"\n"; } DWORD WINAPI put(LPVOID param) { int j=0; do { WaitForSingleObject(Empty,INFINITE); WaitForSingleObject(mutex,INFINITE); std::cout<<GetCurrentThreadId()<<"---"<<j<<"---"; queue_.push_back(2); output(); j++; ReleaseSemaphore(mutex,1, NULL); ReleaseSemaphore(full,1, NULL); } while (j!=10); return 0; } DWORD WINAPI take(LPVOID param) { int j=0; do { WaitForSingleObject(full,INFINITE); WaitForSingleObject(mutex,INFINITE); std::cout<<GetCurrentThreadId()<<"---"<<j<<"---"; while (queue_.empty()) { return 0; } queue_.pop_front(); output(); j++; ReleaseSemaphore(mutex,1, NULL); ReleaseSemaphore(Empty,1, NULL); } while (j!=10); return 0; } int main() { int i; Empty=CreateSemaphore(NULL,10,10,NULL); full=CreateSemaphore(NULL,0,10,NULL); mutex=CreateSemaphore(NULL,1,1,NULL); DWORD * ThreadId=(DWORD *)malloc(10*sizeof(DWORD*)); HANDLE* ThreadHandle=(HANDLE*)malloc(10*sizeof(HANDLE)); for (i=0;i<5;i++) { ThreadHandle[i+5]=CreateThread(NULL,0,put,NULL,0,&ThreadId[i+5]); ThreadHandle[i]=CreateThread(NULL,0,take,NULL,0,&ThreadId[i]); } WaitForMultipleObjects(10,ThreadHandle,TRUE,INFINITE); getch(); return 0; }