VLink 2.0.0
A high-performance communication middleware
Loading...
Searching...
No Matches
condition_variable.h File Reference

POSIX monotonic-clock condition variable replacing std::condition_variable. More...

#include <condition_variable>
#include <memory>
#include <utility>
Include dependency graph for condition_variable.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Namespaces

Typedefs

using vlink::ConditionVariable = std::condition_variable
using vlink::ConditionVariableAny = std::condition_variable_any
using vlink::condition_variable = ConditionVariable
using vlink::condition_variable_any = ConditionVariableAny

Detailed Description

POSIX monotonic-clock condition variable replacing std::condition_variable.

On older versions of GCC (and some libc implementations) std::condition_variable internally uses CLOCK_REALTIME for timed waits, which means that NTP adjustments or system-clock changes can cause spurious wakeups or missed timeouts. This header provides vlink::ConditionVariable and vlink::ConditionVariableAny as drop-in replacements that explicitly configure the underlying pthread_cond_t to use CLOCK_MONOTONIC via pthread_condattr_setclock.

On non-POSIX platforms (Windows) the types are aliased to their std:: counterparts because that bug does not apply there.

Type aliases for convenience:

The public API is identical to std::condition_variable and std::condition_variable_any respectively, so existing code can substitute the types without further changes.

Note
  • On POSIX the ConditionVariable is backed by a raw pthread_cond_t initialised with CLOCK_MONOTONIC. It is not copyable or movable.
  • ConditionVariableAny uses a shared internal ConditionVariable plus a std::mutex, making it compatible with any BasicLockable type.
  • The ceil() / ceil_impl() helper functions ensure that duration conversions always round up, preventing premature timeouts.
Example
std::mutex mtx;
bool ready = false;
// Consumer thread:
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, std::chrono::milliseconds(200),
[&]{ return ready; });
}
// Producer thread:
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();