Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 11 alternative pthread_cond_timedwait

I need to make a thread waiting until either

  • a timeout is expired, or
  • a variable is changed by another thread

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?

like image 348
Cob013 Avatar asked Apr 15 '13 11:04

Cob013


People also ask

What is pthread_cond_timedwait?

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.

Is it or is it not necessary to re check the predicate condition for a critical section after returning from Pthread_cond_wait ()? Why?

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.

What does pthread cond broadcast do?

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.

What is pthread condition variable?

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.


1 Answers

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
like image 92
Kerrek SB Avatar answered Sep 28 '22 10:09

Kerrek SB