Condition variables

Discussions and support about ChibiOS/RT, the free embedded RTOS.
Post Reply
Captain
Posts: 12
Joined: Sat Dec 19, 2015 3:21 pm

Condition variables

Post by Captain »

Hello all. Sorry for asking here, as the question is not related exactly with ChibiOS, but rather theoretical. In my struggle to clarify the topic, I have looked through lots of examples. Most of it are just "consumer/producer" examples where one thread "feeds" data into another through a fifo pipe. The idea is clear enough, but why complicate things, if Chibi have Mailbox (Queue) mechanism, that works the same way, what is the difference?
Well, what I'm trying to do is to create several threads, sharing single memory region (without FIFO). One of those threads should always wait on the data in this region to be updated from other threads (and, let's say, send this data over serial upon update). Is this the case to use cond vars? Here is my approach:

Code: Select all

thread_t thread_that_sends_data_over_serial() {
  while(true) {
    chMtxLock(&Mtx);
    chCondWait(&dataUpdated);
    ... perform blocking transmission ...
    chMtxUnlock(&Mtx);
  }
}

thread_t t1/t2/t3/t4...() {
    while(true) {
       ... do something ...
       chMtxLock(&Mtx);
       ... write data to the memory region ...
       chCondSignal(&dataUpdated);
       chMtxUnlock(&Mtx);
       ... do something ...
    }
}

Am I right in assumptions, that:
1. thread_that_sends_data_over_serial will block on chCondWait until any single thread (t1/t2/t3 etc) will lock the mutex and execute chCondSignal?
2. threads t1/t2/t3 etc will not interfere - as soon as t1 will unlock the mutex, thread_that_sends_data_over_serial will lock it and prevent other threads from changing the data?
Again, sorry for newbie questions here... :roll:
User avatar
Giovanni
Site Admin
Posts: 14891
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 996 times

Re: Condition variables

Post by Giovanni »

Hi,

Condition variables are implemented for compatibility with the equivalent Posix mechanims, few RTOSes have them and are not used very often. ChibiOS/RT strives for completeness and generality so those are implemented.

I recommend this article on Wikipedia: https://en.wikipedia.org/wiki/Condition_variables

Note that your example is not complete, before going to sleep on the condition variable some kind of condition should be checked (that would be the protected condition variable).

Giovanni
Post Reply