10 #include <condition_variable>
17 namespace ThreadedMailbox {
23 std::condition_variable m_condition;
24 unsigned long m_count = 0;
29 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
35 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
37 m_condition.notify_one();
42 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
44 m_condition.wait(lock);
49 bool wait_for(std::chrono::milliseconds timeout_ms) {
50 std::cv_status l_Stat = std::cv_status::no_timeout;
51 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
52 while (!m_count && l_Stat == std::cv_status::no_timeout)
53 l_Stat = m_condition.wait_for(lock, timeout_ms);
54 if (l_Stat == std::cv_status::no_timeout)
56 return (l_Stat == std::cv_status::no_timeout);
61 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
70 template <
typename MsgT>
74 std::queue<MsgT> m_MsgQ;
82 bool l_em = m_MsgQ.empty();
89 std::queue<MsgT> l_Empty;
90 std::swap(m_MsgQ, l_Empty);
113 bool l_Success =
false;
129 std::thread m_Thread;
131 std::chrono::milliseconds m_Period_ms;
134 std::function<void(
void)> m_NotifyEvent;
141 CTimer(
const std::function<
void(
void)> & rTimerEventNotifierFunction)
142 : m_NotifyEvent(rTimerEventNotifierFunction)
145 template<
class Fn,
class... Args>
146 CTimer(Fn&& rTimerEventNotifierFunction, Args&&... Ax)
147 : m_NotifyEvent(std::bind(rTimerEventNotifierFunction, Ax...))
159 bool l_Aborted = m_AbortSem.
wait_for(m_Period_ms);
179 std::lock_guard<decltype(m_Lock)> l_lg(m_Lock);
181 if (m_Thread.joinable())
185 m_Period_ms = Delay_ms;
187 m_Thread = std::thread(&CTimer::ThreadMain,
this);
190 bool Start(std::chrono::milliseconds Period_ms)
192 std::lock_guard<decltype(m_Lock)> l_lg(m_Lock);
194 if (m_Thread.joinable())
197 m_SingleShot =
false;
198 m_Period_ms = Period_ms;
200 m_Thread = std::thread(&CTimer::ThreadMain,
this);
205 std::lock_guard<decltype(m_Lock)> l_lg(m_Lock);
207 if (m_Thread.joinable())
221 template <
typename UserMsgT>
235 sMailBoxMsg(
eEventType EvtType,
const UserMsgT & rMsg)
236 : Evt(EvtType), UserMsg(rMsg)
247 CMailBox<sMailBoxMsg> m_MailBox;
248 std::thread m_Thread;
249 std::atomic<bool> m_RequestedToStop;
258 : m_RequestedToStop(false)
279 template <
typename UserMsgT>
282 if (!m_Thread.joinable())
285 m_RequestedToStop =
false;
286 m_Thread = std::thread(&CThreadedMailBox::l_ThreadMain,
this);
290 template <
typename UserMsgT>
293 m_RequestedToStop =
true;
294 m_MailBox.push(sMailBoxMsg(eEventType::kExit));
295 if (m_Thread.joinable() && std::this_thread::get_id() != m_Thread.get_id())
299 template <
typename UserMsgT>
302 m_MailBox.push(sMailBoxMsg(eEventType::kUserMsg, rMsg));
305 template <
typename UserMsgT>
308 return m_RequestedToStop;
311 template <
typename UserMsgT>
315 bool l_RunWorkerThread =
true;
316 while (l_RunWorkerThread)
321 case eEventType::kExit:
322 l_RunWorkerThread =
false;
323 l_ThreadTask(Msg.Evt,
nullptr);
325 case eEventType::kUserMsg:
326 l_ThreadTask(Msg.Evt, &Msg.UserMsg);