所以我设法让我的程序运行,但由于某种原因,除非他/她之前的顾客先离开酒吧,否则没有顾客走进酒吧,我该如何解决?我尝试了一个 mutex_lock 但我可能实施错了,这是我到目前为止的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem;
pthread_mutex_t serve = PTHREAD_MUTEX_INITIALIZER;
void Bartender(int);
void EnterBar(int);
void OrderStart(int);
void ServeStart(int);
void ServeDone(int);
void OrderDone(int);
void DrinkBeer(int);
void LeaveBar(int);
void* Customer(void*);
void Bartender(int cid)
{
ServeStart(cid);
ServeDone(cid);
}
void* Customer(void* id)
{
int cid =(int)id;
EnterBar(cid);
LeaveBar(cid);
return NULL;
}
void EnterBar(int cid){
sem_wait(&sem); //decrease semaphore
printf("Customer %d enters the bar.\n", cid);
int cups;
for(cups=0;cups<(cid%3+1);cups++){
pthread_mutex_lock(&serve);
OrderStart(cid);
OrderDone(cid);
DrinkBeer(cid);
pthread_mutex_unlock(&serve);
}
}
void OrderStart(int cid)
{
printf("Customer %d asks for beer.\n", cid);
Bartender(cid);
}
void OrderDone(int cid)
{
printf("Customer %d gets the beer.\n", cid);
}
void DrinkBeer(int cid)
{
printf("Customer %d drinks the beer.\n", cid);
}
void LeaveBar(int cid)
{
printf("Customer %d leaves the bar.\n", cid);
sem_post( &sem ); //increase semaphore
}
void ServeStart(int cid)
{
printf("Bartender starts to serve customer %d.\n", cid);
}
void ServeDone(int cid)
{
printf("Bartender is done serving customer %d.\n", cid);
}
int main (int argc, char *argv[])
{
int t;
long rc;
int num_customers = atoi(argv[1]); //number of customers
int capacity = atoi(argv[2]); //bar capacity
if(num_customers > 0 && capacity > 0){
rc = sem_init( &sem, 0, capacity );
if (rc)
{
printf("ERROR; return code from sem_init() is %ld\n",rc);
exit(-1);
}
//pthread_t threads[num_customers];
pthread_t *threads = (pthread_t*)malloc(num_customers*sizeof(pthread_t));
if(random() > RAND_MAX / 2)
usleep(1);
//rc = sem_init(&sem1,0,capacity);
//rc = pthread_barrier_init(&barrier1, NULL, num_customers);
for(t=0; t<num_customers;t++){
printf("In main: creating thread %d\n", t);
//printf("CAPACITY: %d\n", capacity);
rc = pthread_create(&threads[t], NULL, Customer, (void* )t);
if (rc){
printf("ERROR; return code from pthread_create() is %ld\n", rc);
exit(-1);
}
}
for( t=0;t<num_customers;t++)
pthread_join(threads[t],NULL);
sem_destroy(&sem); //destroy semaphore
}
else{
printf("ERROR: Both parameters should be a valid positive numbers.");
exit(-1);
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
它应该允许酒吧里的多个顾客,并在喝完啤酒后离开,而不是在顾客离开之前离开。调酒师需要一根线吗?有什么建议么??