2017-01-24 21:19:52 +01:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include "types.h"
|
|
|
|
#include "Atomic.h"
|
|
|
|
|
|
|
|
// Lightweight condition variable
|
|
|
|
class cond_variable
|
|
|
|
{
|
|
|
|
// Internal waiter counter
|
|
|
|
atomic_t<u32> m_value{0};
|
|
|
|
|
|
|
|
protected:
|
|
|
|
// Internal waiting function
|
|
|
|
bool imp_wait(u32 _old, u64 _timeout) noexcept;
|
|
|
|
|
|
|
|
// Try to notify up to _count threads
|
|
|
|
void imp_wake(u32 _count) noexcept;
|
|
|
|
|
|
|
|
public:
|
|
|
|
constexpr cond_variable() = default;
|
|
|
|
|
|
|
|
// Intrusive wait algorithm for lockable objects
|
2016-09-07 00:38:52 +02:00
|
|
|
template <typename T>
|
2017-01-24 21:19:52 +01:00
|
|
|
explicit_bool_t wait(T& object, u64 usec_timeout = -1)
|
|
|
|
{
|
|
|
|
const u32 _old = m_value.fetch_add(1); // Increment waiter counter
|
2016-09-07 00:38:52 +02:00
|
|
|
object.unlock();
|
2017-01-24 21:19:52 +01:00
|
|
|
const bool res = imp_wait(_old, usec_timeout);
|
2016-09-07 00:38:52 +02:00
|
|
|
object.lock();
|
2017-01-24 21:19:52 +01:00
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wake one thread
|
|
|
|
void notify_one() noexcept
|
|
|
|
{
|
|
|
|
if (m_value)
|
|
|
|
{
|
|
|
|
imp_wake(1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wake all threads
|
|
|
|
void notify_all() noexcept
|
|
|
|
{
|
|
|
|
if (m_value)
|
|
|
|
{
|
|
|
|
imp_wake(-1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|