我正在尝试创建一个简单的酒吧程序,其中一定数量的客户可以同时在酒吧内。每次客户要啤酒时,调酒师都应该为客户提供啤酒。
出于某种原因,在我的程序中,酒吧服务员在顾客离开酒吧后为顾客服务
我怎样才能解决这个问题?有什么建议么?
这是我的代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h> //for declaration of exit()
#include <semaphore.h> //to use semaphores
pthread_mutex_t serve = PTHREAD_MUTEX_INITIALIZER;
pthread_barrier_t barrier1;
sem_t OktoEnter;
int cid = 0;
void EnterBar();
void OrderStart();
void ServeStart();
void ServeDone();
void OrderDone();
void DrinkBeer();
void LeaveBar();
void* Bartender(void *arg)
{
ServeStart();
ServeDone();
}
void* Customer(void* id)
{
cid =(int)id;
EnterBar();
LeaveBar();
}
void EnterBar(){
printf("Customer %d enters the bar.\n", cid);
int cups;
pthread_t order;
for(cups=0;cups<(cid%3+1);cups++){
pthread_mutex_lock(&serve);
OrderStart();
OrderDone();
DrinkBeer();
pthread_mutex_unlock(&serve);
}
//decrease semaphore
}
void OrderStart(){
pthread_t order;
printf("Customer %d asks for beer.\n", cid);
int rc = pthread_create(&order, NULL, Bartender, NULL);
}
void OrderDone(){
printf("Customer %d gets the beer.\n", cid);
}
void DrinkBeer(){
printf("Customer %d drinks the beer.\n", cid);
}
void LeaveBar(){
printf("Customer %d leaves the bar.\n", cid);
//increase semaphore
}
void ServeStart(){
printf("Bartender starts to serve customer %d.\n", cid);
}
void ServeDone(){
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){
pthread_t threads[num_customers];
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);
rc = pthread_create(&threads[t], NULL, Customer, (void* )t);
if (rc){
printf("ERROR; return code from pthread_create() is %ld\n", rc);
exit(-1);
}
}
}
else{
printf("ERROR: Both parameters should be a valid positive numbers.");
exit(-1);
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
我一直在改变功能,但它不能正常工作。