一個生產者生產產品,多個消費者同時獲得產品
阿新 • • 發佈:2018-12-30
void * produce(void *ptr)
{
for (int i = 0; i < 20; ++i)
{
pthread_rwlock_wrlock(&sharedData.rwlock);
sharedData.product = i;
pthread_rwlock_unlock(&sharedData.rwlock);
sem_post(&bin_sem1);
sem_post(&bin_sem2);
sem_post(&bin_sem3);
sleep(1);
}
}
void * consume1(void *ptr)
{
while(1)
{
sem_wait(&bin_sem1);
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume1:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
}
}
void * consume2(void *ptr)
{
while(1)
{
sem_wait(&bin_sem2);
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume2:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
}
}
void * consume3(void *ptr)
{
while(1)
{
sem_wait(&bin_sem3);
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume3:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
}
}
{
for (int i = 0; i < 20; ++i)
{
pthread_rwlock_wrlock(&sharedData.rwlock);
sharedData.product = i;
pthread_rwlock_unlock(&sharedData.rwlock);
sem_post(&bin_sem1);
sem_post(&bin_sem2);
sem_post(&bin_sem3);
sleep(1);
}
}
void * consume1(void *ptr)
{
while(1)
{
sem_wait(&bin_sem1);
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume1:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
}
}
void * consume2(void *ptr)
{
while(1)
{
sem_wait(&bin_sem2);
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume2:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
}
}
void * consume3(void *ptr)
{
while(1)
{
sem_wait(&bin_sem3);
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume3:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
}
}