I feel like i'm not understanding something about mutexes and conditions. If i have a thread that waits for a condition before it starts operating on something, why should the other thread lock the mutex before signaling the condition to have the thread start its operation? I understand that we would lock the mutex before signaling if we were setting a variable that the other thread reads, but if we are only using the mutex and condition to tell the other thread when to stop "sleeping", i don't see why we would need to lock the mutex before signaling the condition
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void thread1()
{
pthread_mutex_lock(&mutex);
for(;;)
{
pthread_cond_wait(&cond, &mutex);
// do stuff
pthread_mutex_lock(&mutex);
}
pthread_mutex_unlock(&mutex);
}
void mainthread()
{
// start thread1
for(;;)
{
// do stuff
// lock the mutex (why?)
pthread_cond_broadcast(&cond);
// unlock the mutex
}
}