資源簡介
假設M個生產者和N個消費者共享一個具有K(K大于1)個緩沖區的循環緩沖結構BUFFER(提示:可以用一個循環隊列或一個整型數組來表示),并設置兩個指針IN和OUT,其中IN指向生產者線程當前可用的空緩沖區的在BUFFER中的下標,OUT指向消費者線程當前可用的滿緩沖區在BUFFER中的下標。生產者線程和消費者線程并發執行,當無空緩沖區時,生產者線程阻塞;當無滿緩沖區時消費者線程阻塞,并且多個生產者線程對IN的使用必須互斥,多個消費者線程對OUT的使用也必須互斥
代碼片段和文件信息
#include?“stdafx.h“
#include???
#include?
#include?
#include?
using?namespace?std;
//設置控制臺輸出顏色
BOOL?SetConsoleColor(WORD?wAttributes)
{
????HANDLE?hConsole?=?GetStdHandle(STD_OUTPUT_HANDLE);
????if?(hConsole?==?INVALID_HANDLE_VALUE)
????????return?FALSE;
????return?SetConsoleTextAttribute(hConsole?wAttributes);
}
int?MNK;?//生產者,消費者,緩沖區的個數
int?ProductID;//生產產品ID
int?ConsumeID;//消費產品ID
int?*g_Buffer;?//緩沖池
int?g_i?g_j;??//緩沖池里的生產者和消費者的指向
HANDLE?Pro_MutexCon_MutexMutex;?
HANDLE?Empty?Full;
SYSTEMTIME?systime;
struct?ThreadInfo
{
int?ID;?//ID
int?delay;
};
ThreadInfo?*Thread_info;
void?ProducerThreadFun(void?*p)
{
????while(true)
????{
DWORD?m_delay;?
m_delay?=?(DWORD)(?((ThreadInfo*)(p))->delay);
Sleep(m_delay*1000);
WaitForSingleobject(EmptyINFINITE);
????????WaitForSingleobject(Pro_MutexINFINITE);
WaitForSingleobject(MutexINFINITE);
int?ID;ID?=?((ThreadInfo*)(p))->ID;
static?int?nextp?=?0;
nextp?=?rand()%100;
????????g_Buffer[g_i]?=?nextp;
SetConsoleColor(FOREGROUND_RED);
cout<<“*******現在執行生產者進程*******“< cout< ????????cout<<“???生產者ID?=?“< cout<<“???投入進緩沖區(緩沖區位置?“< cout< cout<<“???產品ID?=?“< cout<<“???當前阻塞生產者進程ID為?“;
for(int?i?=?0;?i? {
if(i+1?!=?ID)
cout< }
cout<
GetLocalTime(&systime);
cout<<“???當前時間“< cout< cout<<“--------------------------------------------------------“< SetConsoleColor(FOREGROUND_RED?|?FOREGROUND_GREEN?|?FOREGROUND_BLUE);
ProductID++;
????????g_i?=?(g_i?+?1)?%?K;
Sleep(2000);
ReleaseMutex(Mutex);
????????ReleaseMutex(Pro_Mutex);
????????ReleaseSemaphore(Full1NULL);
????}
????printf(“生產者完成任務,線程結束運行\n“);
}
void?ConsumerThreadFun(void?*p)??
{
????while(true)
{
static?int?nextc?=?0;
DWORD?m_delay;
m_delay?=?(DWORD)(?((ThreadInfo*)(p))->delay);
Sleep(m_delay*1000);
????????WaitForSingleobject(Full?INFINITE);
????????WaitForSingleobject(Con_MutexINFINITE);
WaitForSingleobject(MutexINFINITE);
int?ID;ID?=?((ThreadInfo*)(p))->ID;
nextc?=?g_Buffer[g_j];
????????SetConsoleColor(FOREGROUND_GREEN);
cout<<“*******現在執行消費者進程*******“< cout< ????????c
- 上一篇:SDS_Function
- 下一篇:《C++ GUI QT編程》教程配套
評論
共有 條評論