Page 1 of 1

Condition variables

Posted: Fri Feb 24, 2017 11:55 pm
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:

Re: Condition variables

Posted: Sat Feb 25, 2017 8:04 am
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