I'm coding to simulate a selling-ticket situation:
Two threads are selling some tickets one by one and one thread is to show sold out
when the number of the tickets is 0.
So I try to use a condition variable. Here is the code:
int a = 10;
pthread_mutex_t mtx;
pthread_cond_t cond;
void * funca(void *p)
{
while(1)
{
pthread_mutex_lock(&mtx);
if (a == 0)
{
break;
}
a--;
pthread_mutex_unlock(&mtx);
sleep(1);
}
pthread_mutex_unlock(&mtx);
pthread_cond_broadcast(&cond);
return NULL;
}
void * funcb(void *p)
{
while(1)
{
pthread_mutex_lock(&mtx);
if (a == 0)
{
break;
}
a--;
pthread_mutex_unlock(&mtx);
sleep(1);
}
pthread_mutex_unlock(&mtx);
pthread_cond_broadcast(&cond);
return NULL;
}
void * funcc(void *p)
{
pthread_mutex_lock(&mtx);
while(a != 0)
{
pthread_cond_wait(&cond, &mtx);
printf("I'm nothing");
}
pthread_mutex_unlock(&mtx);
printf("sold out\n");
return NULL;
}
However, when I execute the code above, I get a infinite loop with many I'm nothing
printed.
You haven't initialised your mutex and condition variable. When you declare the variables, use:
There's also no point having two identical functions for
funca()
andfuncb()
, you can just have two different threads execute the same function.