Question about Condition Variables

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

Post Reply
dismirlian
Posts: 65
Joined: Fri Dec 20, 2013 3:59 pm
Has thanked: 1 time
Been thanked: 16 times

Question about Condition Variables

Post 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.
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Question about Condition Variables

Post 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
dismirlian
Posts: 65
Joined: Fri Dec 20, 2013 3:59 pm
Has thanked: 1 time
Been thanked: 16 times

Re: Question about Condition Variables

Post 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.
Post Reply