mirror of
https://codeberg.org/comaps/comaps
synced 2025-12-23 22:53:43 +00:00
committed by
Konstantin Pastbin
parent
c9cbb64f12
commit
76ffc99abd
79
libs/base/waiter.hpp
Normal file
79
libs/base/waiter.hpp
Normal file
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
||||
namespace base
|
||||
{
|
||||
// Class for multithreaded interruptable waiting.
|
||||
class Waiter
|
||||
{
|
||||
public:
|
||||
enum class Result
|
||||
{
|
||||
PreviouslyNotified,
|
||||
Timeout,
|
||||
NoTimeout
|
||||
};
|
||||
|
||||
void Wait()
|
||||
{
|
||||
std::unique_lock lock(m_mutex);
|
||||
|
||||
if (m_notified)
|
||||
return;
|
||||
|
||||
m_event.wait(lock, [this]() { return m_notified; });
|
||||
}
|
||||
|
||||
template <typename Rep, typename Period>
|
||||
Result Wait(std::chrono::duration<Rep, Period> const & waitDuration)
|
||||
{
|
||||
std::unique_lock lock(m_mutex);
|
||||
|
||||
if (m_notified)
|
||||
return Result::PreviouslyNotified;
|
||||
|
||||
auto const result = m_event.wait_for(lock, waitDuration, [this]() { return m_notified; });
|
||||
|
||||
return result ? Result::NoTimeout : Result::Timeout;
|
||||
}
|
||||
|
||||
void Notify()
|
||||
{
|
||||
SetNotified(true);
|
||||
|
||||
m_event.notify_all();
|
||||
}
|
||||
|
||||
void Reset()
|
||||
{
|
||||
SetNotified(false);
|
||||
}
|
||||
|
||||
private:
|
||||
void SetNotified(bool notified)
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
m_notified = notified;
|
||||
}
|
||||
|
||||
bool m_notified = false;
|
||||
std::mutex m_mutex;
|
||||
std::condition_variable m_event;
|
||||
};
|
||||
|
||||
inline std::string DebugPrint(Waiter::Result result)
|
||||
{
|
||||
switch (result)
|
||||
{
|
||||
case Waiter::Result::PreviouslyNotified: return "PreviouslyNotified";
|
||||
case Waiter::Result::NoTimeout: return "NoTimeout";
|
||||
case Waiter::Result::Timeout: return "Timeout";
|
||||
default: ASSERT(false, ("Unsupported value"));
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
} // namespace base
|
||||
Reference in New Issue
Block a user