#include<iostream>
#include<vector>
using namespace std;
//定义缓冲区大小
#define MAX_SIZE 20
int Buffer[MAX_SIZE];
//全局变量
int in,out;
int Sin = MAX_SIZE;
int Sout = 0;
int mutex = 1;
void P( int &i ); //P操作
void V( int &i ); //V操作
void display(); //显示缓冲区内容
class Producer
{
public:
Producer( int &value );
int load_value(); //向缓冲区内输入元素
int return_value() { return x; }
private:
static int n;
int x;
static vector<Producer> pro; //模拟生产者的阻塞队列
};vector<Producer> Producer::pro;
Producer ::Producer( int &value )
{
x = value;
}
int Producer::load_value()
{
if( Sin > 0 )
{
P(Sin);
if( mutex == 1 && pro.size() == 0 ) //信号量为1并且阻塞队列里没有等待的进程时,运行当前进程
{
P(mutex);
Buffer[in] = x;
in = (in+1) % MAX_SIZE;
V(mutex);
V(Sout);
}
else if( pro.size() != 0 ) //信号量为1且阻塞队列里有等待的进程时,先执行阻塞队列的第一个进程,并且把当前进程添加到阻塞 //队列
{ //队列,执行完成后删除第一个已执行的进程
pro.push_back(*this);
int i = pro[0].return_value();
P(mutex);
Buffer[in] = i;
in = (in+1) % MAX_SIZE;
V(mutex);
V(Sout);
pro.erase( pro.begin() );
}
else //信号量为0时,将该进程添加到阻塞队列
pro.push_back(*this);
return 0;
}
}
class Consumer
{
public:
int get_value(int &x); //取出缓冲区的数据,成功返回0,并将取出的数据放入x,失败返回-1
private:
int x;
static vector<Consumer> con;
};vector<Consumer> Consumer::con;
int Consumer::get_value( int &x )
{
if( Sout > 0 )
{
P(Sout);
if( mutex == 1 && con.size() == 0 )
{
P(mutex);
x = Buffer[out];
out = (out+1) % MAX_SIZE;
V(mutex);
V(Sin);
}
else if( con.size() != 0 )
{
P(mutex);
con[0].x = Buffer[out];
out = (out+1) % MAX_SIZE;
V(mutex);
V(Sin);
}
else
con.push_back( *this );
}
return 0;
}
int main()
{
int i,j;
Producer p( i=3 ),p1( i=5 );
p.load_value();
p1.load_value();
display();
Consumer c,c1;
c.get_value(j);
cout << "取出的数据为: " << j << endl;
c1.get_value(j);
cout << "取出的数据为: " << j << endl;
display();
getchar();getchar();
return 0;
}
void P(int &i )
{
i = i-1;
}
void V(int &i )
{
i = i+1;
}
void display()
{
cout << "缓冲区数据为: ";
for( int i = 0; i < Sout; i++ )
cout << Buffer[i] << " ";
cout << "空闲缓冲区为: " << Sin << " 个" << endl;
}
这里我想问下如何来模拟多进程呢,就比如一个生产者正在运行的,而另一个生产者或消费者也要运行,但是生产者还没运行完,只能将自己挂起