Em chạy nhiều lần ra nhiều kết quả khác nhau. Em nghĩ là em bị sai logic nhưng mà không biết cách sửa mong mọi người góp ý ạ. Đây là những output mà em chạy.
- both barbers are sleeping
- customer remaining = 0, next_barber = 1
- customer remaining = 1, next_barber = 0
- customer remaining = 1, next_barber = 1
- customer remaining = 0, next_barber = 0
#define NUM_BARBERS 2 // Number of barbers
#define NUM_CHAIRS 3 // Number of chairs in the waiting room
#define NUM_CUSTOMERS 5 // Total number of customers
chan waitingRoom = [NUM_CHAIRS] of {int}; // Bounded FIFO channel for waiting customers
chan barber[NUM_BARBERS] = [0] of {int}; // Synchronous channels for barber-customer interaction
chan finished[NUM_BARBERS] = [0] of {int}; // Synchronous channels to signal haircut completion
int customers_remaining = NUM_CUSTOMERS; // Track the total number of customers left
int next_barber = 0; // Keep track of the next barber to pick a customer (round-robin)
proctype Barber() {
int barber_id = _pid - 1;
int customer_id;
do
:: len(waitingRoom) > 0 ->
atomic {
waitingRoom?customer_id;
printf("Barber %d is cutting hair for Customer %d.\n", barber_id, customer_id);
}
atomic {
barber[barber_id]!customer_id;
finished[barber_id]?customer_id;
printf("Barber %d finished haircut for Customer %d.\n", barber_id, customer_id);
}
:: atomic{
customers_remaining == 0 && len(waitingRoom) == 0 ->
printf("Barber %d is sleeping.\n", barber_id);
break;
}
od;
}
proctype Customer() {
int customer_id = _pid - 1;
int barber_id;
if
:: len(waitingRoom) < NUM_CHAIRS ->
atomic {
waitingRoom!customer_id;
printf("Customer %d is waiting.\n", customer_id);
}
atomic {
barber_id = next_barber; // Assign to the next barber
next_barber = (next_barber + 1) % NUM_BARBERS; // Update for round-robin
}
barber[barber_id]?customer_id; // Wait for the barber to accept
printf("Customer %d is having a haircut with Barber %d.\n", customer_id, barber_id);
finished[barber_id]!customer_id; // Signal haircut completion
printf("Customer %d is leaving after haircut from Barber %d.\n", customer_id, barber_id);
atomic{
customers_remaining--;
}
:: else ->
atomic {
printf("Customer %d found no chair and left.\n", customer_id);
customers_remaining--;
}
fi;
}
init {
atomic {
printf("The barbers are sleeping\n");
// Start barber processes
int i;
for (i : 1 .. NUM_BARBERS) {
run Barber();
}
// Start customer processes
for (i : 1 .. NUM_CUSTOMERS) {
run Customer();
}
}
}