Page 1 of 1

Question about Condition Variables

Posted: Fri Feb 20, 2015 6:14 pm
by dismirlian
Hello all, I have a question regarding the usage of Condition Variables.

I have a producer-consumer problem. Imagine a producer thread inserting elements in a FIFO, and a consumer thread removing those elements. I have a mutex protecting the FIFO access, one condition variable (cvSpaceAvailable) to wait for room to insert one element, and other condition variable (cvDataAvailable) which signals availability of elements. My code looks roughly like this:

Code: Select all

producer_thread() {

    for (;;) {
        chMtxLock(&mutex);
        while (free_space_in_fifo == 0) {
            chCondWait(&cvSpaceAvailable);
        }

        insert_element();

        chCondSignal(&cvDataAvailable);
        chMtxUnlock(&mutex);
    }

}

consumer_thread() {

    for (;;) {
        chMtxLock(&mutex);
        while (number_of_elements_in_fifo == 0) {
            chCondWait(&cvDataAvailable);
        }

        remove_element();

        chCondSignal(&cvSpaceAvailable);
        chMtxUnlock(&mutex);
    }

}


My question is: should I be signaling the condition variables with the mutex locked (as in the code above), or with the mutex unlocked (Unlock then Signal)? Are there any advantages for either alternative?

Thank you very much!

Diego.

Re: Question about Condition Variables

Posted: Fri Feb 20, 2015 6:35 pm
by Giovanni
It is a classic problem, the variable is signaled from within.

I don't know if you already saw it but it is here too: http://en.wikipedia.org/wiki/Monitor_%2 ... ization%29

Giovanni

Re: Question about Condition Variables

Posted: Fri Feb 20, 2015 7:13 pm
by dismirlian
Hi Giovanni, thanks for your quick answer.

Yes, in fact, I've seen the Wikipedia article, and my question popped up while reading it. This webpage (http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/) poses the same question, and gives an answer in favour of signaling the condvar from within the locked region, as you suggest. There are some interesting comments at the bottom of the article, which give more reasons to Signal->Unlock. Part of the analysis is specific to pthreads, but I think the basic concept applies to ChibiOS.

In any case, I'll follow your suggestion.

Thanks for your time! :)

Diego.