Reputation: 12371
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.
Upvotes: 0
Views: 90
Reputation: 239011
You haven't initialised your mutex and condition variable. When you declare the variables, use:
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
There's also no point having two identical functions for funca()
and funcb()
, you can just have two different threads execute the same function.
Upvotes: 3