1

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
    }
}
iedoc
  • 2,266
  • 3
  • 30
  • 53
  • [Why do you use pthreads then](http://en.cppreference.com/w/cpp/thread)? – Ivan Aksamentov - Drop Oct 29 '15 at 14:20
  • 1
    You don't need to, see [this](http://stackoverflow.com/questions/4544234/calling-pthread-cond-signal-without-locking-mutex) – yngccc Oct 29 '15 at 14:26
  • 1
    I don't have a lot of time to rewrite the codebase to use c++11's thread interface, unless theres a good reason to use std::thread over pthread_t – iedoc Oct 29 '15 at 14:26
  • yngum, thats exactly my question, i searched for it but wasn't able to find anything, thank you – iedoc Oct 29 '15 at 14:27
  • this is a dupliciate of http://stackoverflow.com/questions/4544234/calling-pthread-cond-signal-without-locking-mutex – iedoc Oct 29 '15 at 14:28

0 Answers0