It's written in POSIX threads tutorial https://computing.llnl.gov/tutorials/pthreads/ that it is a logical error.
my question is why it is a logical error?
In my program i need to use these signals, however i cannot guarantee that there will be a thread that will be in _cond_wait state. I tried to test it and nothing happens. Is this can cause unexpected behavior or worse?
thank you!
The pthread_cond_signal() function wakes up at least one thread that is currently waiting on the condition variable specified by cond. If no threads are currently blocked on the condition variable, this call has no effect.
Condition variables are synchronization primitives that enable threads to wait until a particular condition occurs. Condition variables are user-mode objects that cannot be shared across processes. Condition variables enable threads to atomically release a lock and enter the sleeping state.
answer: a)The solution makes threads to check a condition and if that condition is true, then the threads go to sleep. When the threads go to sleep, they execute the wait() operation. ... When the thread using the lock releases it, then it notifies all the threads in the waiting queue.
In C under Linux, there is a function pthread_cond_wait() to wait or sleep.
The answer of blaze comes closest, but is not totally clear:
conditional variables should only be used to signal a change in a condition.
Thread 1 checks a condition. If the condition doesn't meet, he waits on the condition variable until the condition meets. Because the condition is checked first, he shouldn't care whether the condition variable was signaled:
pthread_mutex_lock(&mutex); while (!condition) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex);
Thread 2 changes the condition and signals the change via the condition variable. He doesn't care whether threads are waiting or not:
pthread_mutex_lock(&mutex); changeCondition(); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond)
The bottom line is: the communication is done via some condition. A condition variable only wakes up waiting threads so they can check the condition.
Examples for conditions:
see also pthread example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With