I wrote the code for sleeping barber problem and it seems to be looking weird…
the code is as follows..
#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
#define MAX_C 10
int a[MAX_C], head=0, tail=0, tmp, tb, tc, count=1;
pthread_mutex_t B;
double time_slot[]={0.125,0.5,0.75,1.00,1.25,1.50,1.75,2.00};
void wait(int a)
{
clock_t g=clock();
while(((float)(clock()-g))/CLOCKS_PER_SEC != time_slot[a]);
}
void barber()
{
printf("barber started\n");
while(1) {
tmp=0;
while(head==tail) {
printf("b\n");
}
tb=rand()%8;
printf("tail:%d\n", tail);
tail=(tail+1)%MAX_C;
wait(tb);
}
}
void customer()
{
printf("customers started\n");
while(1) {
wait(rand()%8);
while((head+1)%MAX_C == tail) {
printf("c\n");
}
a[head]=count-1;
printf("head:%d\n", head);
head=(head+1)%MAX_C;
}
}
int main(int argc, char* argv[])
{
pthread_t b,c;
pthread_mutex_init(&B, NULL);
pthread_create(&c, NULL, (void*)&customer, NULL);
pthread_create(&b, NULL, (void*)&barber, NULL);
pthread_join(b, NULL);
pthread_join(c, NULL);
exit(0);
}
The problem is that when the buffer is full … the barber is waiting for customers… but the customer is not executing at all!!( it is neither waiting nor filling the buffer)… coz the customers while loop was not executing…
As Daneil Fischer said … there was a mistake with
while(((float)(clock()-g))/CLOCKS_PER_SEC != time_slot[a]);i should replace it withBut its still weird that this ‘missing’ of the clock value is occuring only after the whole buffer is filled….