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.