在buffer.h中的代码如下:
typedef int buffer_item;
#define BUFFER_SIZE 5
#define MAX_PRODUCER 20
#define MAX_CONSUMER 20
在MainDriver.cpp中的代码如下:
#include
#include
#include
#include
#include
typedef int buffer_item;
#define BUFFER_SIZE 5
#define MAX_PRODUCER 20
#define MAX_CONSUMER 20
pthread_mutex_t mutex;
sem_t hEmpty;
sem_t hFull;
pthread_t hProducer[MAX_PRODUCER];
pthread_t hConsumer[MAX_CONSUMER];
buffer_item buffer[BUFFER_SIZE];
int in=0; int out=0;
void get_Condition( int& t, int& p,
int& c )
{
cout<
sleep before terminating\n";
cin>>t;
cout<
number of producer threads to create\n";
cin>>p;
cout<
number of consumer threads to create\n";
cin>>c;
cout<
}
void Randomize()
{
srand((unsigned int)(time(NULL)%10000));
}
int insert_item( buffer_item item )
{
if( (in+1)%(BUFFER_SIZE+1)==out)
return 1;
buffer[in]=item;
in=(in+1)%(BUFFER_SIZE+1);
return 0;
}
int remove_item( buffer_item* item )
{
if(in==out)
return
1;
*item=buffer[out];
out=(out+1)%BUFFER_SIZE;
return 0;
}
void *producer( void* param )
{
int*
p=(int*)param;
buffer_item rand_num;
while(true)
{ sem_wait(&hEmpty); //Empty iniatal as 5
pthread_mutex_lock(&mutex);
rand_num=rand()%100+p[0];
cout<
"<
want to produce: "<
if(insert_item(rand_num))
cout<
error condition\n";
else
{
cout<
"<
produced
"<
cout<
"<
task done\n";
}
pthread_mutex_unlock(&mutex);
sem_post(&hFull);
cout<
usleep(1000);
}
return
0;
}
void *consumer( void* param )
{
int* p=(int*)param;
buffer_item rand_num;
while(true)
{
sem_wait(&hFull);
pthread_mutex_lock(&mutex);
cout<
"<
want to consumer: "<
if(remove_item(&rand_num))
cout<
error condition\n";
else
{
cout<
"<
consumed
"<
cout<
"<
task done!\n";
}
pthread_mutex_unlock(&mutex);
sem_post(&hEmpty);
cout<
usleep(1000);
}
return
0;
}
void create_Producer( int num )
{
for( int i=0; i
{
int* a=new int[1];
a[0]=i;
pthread_create(&hProducer[i],NULL,producer,a);
usleep(10);
}
}
void create_Consumer( int num )
{
for( int i=0; i
{
int* b=new int[1];
b[0]=i;
pthread_create(&hConsumer[i],NULL,consumer,b);
usleep(10);
}
}
int main()
{
sem_init(&hEmpty,0,BUFFER_SIZE);
sem_init(&hFull,0,1);
pthread_mutex_init(&mutex,NULL);
int time_sleep,pro_num,con_num;
get_Condition(time_sleep, pro_num,
con_num);
Randomize();
create_Producer( pro_num );
create_Consumer( con_num );
for( int i=0; i
pthread_join(hProducer[i],NULL);
for( int j=0; j
pthread_join(hConsumer[j],NULL);
usleep(time_sleep);
exit(1);
return 0;
}