mirror of https://github.com/LX3JL/xlxd.git
Second patch in the improve-shutdown series. This replaces blocking
sleeps with the use of condition variables for signaling thread
shutdown. The details are:
(1) Create CSimpleCondition class to provide a very basic (simple)
condition variable that can be used in situations where external
mutex control is not required, i.e., the class contains both a
managed mutex and condition variable. Instances of this class
can be used for basic signaling, and waiters can specify user
defined predicates.
(2) Replace instances of large sleeps in worker threads with use of
CSimpleCondition. This allows for very quick response times from
worker threads when a shutdown has been initiated.
(3) Change stop thread booleans to atomic_bool.
(4) Fixes small whitespace discprencies.
pull/232/head
parent
76497403e0
commit
9a37f2c680
@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
||||
class CSimpleCondition final
|
||||
{
|
||||
public:
|
||||
CSimpleCondition() : m_Mutex(), m_Condition() {}
|
||||
CSimpleCondition(const CSimpleCondition&) = delete;
|
||||
CSimpleCondition& operator=(const CSimpleCondition&) = delete;
|
||||
CSimpleCondition(CSimpleCondition&&) = delete;
|
||||
~CSimpleCondition() {};
|
||||
|
||||
// Wait up to @duration to be signaled, or until @predicate is true.
|
||||
// Returns result of predicate after timing out or being signaled.
|
||||
template<typename Duration, typename Predicate>
|
||||
bool wait(Duration, Predicate);
|
||||
|
||||
// Signal waiters. If @all is true, all waiters will be woken up.
|
||||
void signal(bool all=true)
|
||||
{
|
||||
if (all)
|
||||
m_Condition.notify_all();
|
||||
else
|
||||
m_Condition.notify_one();
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex m_Mutex;
|
||||
std::condition_variable m_Condition;
|
||||
};
|
||||
|
||||
// Note: @timeout is a relative duration, e.g., "30s".
|
||||
template<typename Duration, typename Predicate>
|
||||
bool CSimpleCondition::wait(Duration timeout, Predicate predicate)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(m_Mutex);
|
||||
auto bound = std::chrono::system_clock::now() + timeout;
|
||||
return m_Condition.wait_until(lock, bound, predicate);
|
||||
}
|
||||
Loading…
Reference in new issue