您的位置:首页 > 编程语言 > C语言/C++

C++模拟“生产者消费者”进程同步问题

2017-06-11 15:49 537 查看
#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <string>
#include <time.h>

using namespace std;

const int limit = 30;  //生产总量
const int maxsize = 10; //缓冲区大小
const int kind = 7;
int bufIdx = 0;    //当前缓冲区下标

string buf[maxsize];    //缓冲区 (字符串)

//伪造的产品
string product[] = {"Apple","Banana","Cherry","Orange","Pear","Peach","WaterMelon"};

HANDLE mutex,full,empty;

HANDLE disp;    //用于控制屏幕打印的互斥锁

//生产者子过程
DWORD WINAPI Producer(LPVOID param)
{
int ct,idx;
const int pwait = 100;
srand(time(NULL)); //随机数播种

WaitForSingleObject(disp, INFINITE);
cout << "Producer Start!" << endl << endl;
ReleaseMutex(disp);

for (ct = 0; ct < limit; ct ++)
{
idx = rand() % kind;

WaitForSingleObject(disp, INFINITE);
cout << product[idx] << " is ready!" << endl << endl;
ReleaseMutex(disp);

WaitForSingleObject(empty, INFINITE); //请求一个空缓冲区,阻塞
WaitForSingleObject(mutex, INFINITE); //请求互斥锁,阻塞
buf[bufIdx ++] = product[idx];

WaitForSingleObject(disp, INFINITE);
cout << product[idx] << " added to slot No. " << bufIdx << endl << endl;
ReleaseMutex(disp);

ReleaseMutex(mutex);    //释放互斥锁
ReleaseSemaphore (full, 1, NULL);   //signal(full)
Sleep(rand() % pwait + 100);  //休息一会
}
cout << "Producer Quit!" << endl << endl;
return 0;
}

//消费者子过程
DWORD WINAPI Consumer(LPVOID param)
{
int ct;
const int cwait = 300;
string stuff;
srand(time(NULL));

WaitForSingleObject(disp, INFINITE);
cout << "Consumer Start!" << endl << endl;
ReleaseMutex(disp);

for (ct = 0; ct < limit; ct ++)
{
WaitForSingleObject(full, INFINITE); //请求一个满缓冲区,阻塞
WaitForSingleObject(mutex, INFINITE); //请求互斥锁,阻塞
stuff = buf[-- bufIdx];

WaitForSingleObject(disp, INFINITE);
cout << "Consumer get " << stuff << " from slot No. " << (bufIdx + 1) << endl << endl;
ReleaseMutex(disp);

ReleaseMutex(mutex);    //释放互斥锁
ReleaseSemaphore (empty, 1, NULL);   //signal(empty)
Sleep(rand() % cwait + 100);  //休息一会
}
cout << "Consumer Quit!" << endl << endl;
return 0;
}

int main()
{
//生产者线程与消费者线程的线程ID
DWORD ProducerID, ConsumerID;
//线程句柄
HANDLE ProducerHandle, ConsumerHandle;

//创建生产者线程
ProducerHandle = CreateThread(NULL, 0, Producer, NULL, 0, &ProducerID);
//创建消费者线程
ConsumerHandle = CreateThread(NULL, 0, Consumer, NULL, 0, &ConsumerID);

disp = CreateMutex(NULL, FALSE, NULL);
//创建互斥锁
mutex = CreateMutex(NULL, FALSE, NULL);
//创建缓冲区占用信号量
full = CreateSemaphore (NULL, 0, maxsize, "full");
//创建缓冲区空闲信号量
empty = CreateSemaphore (NULL, maxsize, maxsize, "empty");

//等待直到生产者线程执行完成
if (ProducerHandle != NULL)
{
WaitForSingleObject(ProducerHandle, INFINIT
4000
E);
CloseHandle(ProducerHandle);
}
//等待直到消费者线程执行完成
if (ConsumerHandle != NULL)
{
WaitForSingleObject(ConsumerHandle, INFINITE);
CloseHandle(ConsumerHandle);
}
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐