I need to make a thread waiting until either
After some research I've found out pthreads got pthread_cond_timedwait which could be useful in this case if I'd be using pthreads.
I'm using C++ 11 threads instead. Is there a suitable alternative for me without completely passing to pthreads?
The pthread_cond_timedwait() function atomically unlocks the mutex and performs the wait for the condition. In this case, atomically means with respect to the mutex and the condition variable and other access by threads to those objects through the pthread condition variable interfaces.
You still need to check your predicate regardless to account for potential spurious wakeups. The purpose of the mutex is not to protect the condition variable; it is to protect the predicate on which the condition variable is being used as a signaling mechanism.
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.
Along with mutexes, pthreads gives us another tool for synchronization between the threads, condition variables. Condition variables are variables of the kind pthread_cond_t. When a thread is waiting on a mutex it will continuously keep polling on the mutex waiting for it to get unlocked.
Yes, you want std::condition_variable
from <condition_variable>
, which has a member function wait_for
that takes a time duration.
The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until:
- a notification is received from another thread
- a timeout expires
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