C++Instrument Catalog MFC 1.2
Metrolab C++InstrumentCatalog for MFC
Loading...
Searching...
No Matches
ThreadedMailbox.h
Go to the documentation of this file.
1
5
6#pragma once
7
8#include <mutex>
9#include <thread>
10#include <condition_variable>
11#include <queue>
12#include <chrono>
13#include <memory>
14#include <atomic>
15#include <functional>
16
17namespace MTL {
18 namespace ThreadedMailbox {
19
21 {
22 private:
23 std::mutex m_mutex;
24 std::condition_variable m_condition;
25 unsigned long m_count = 0; // Initialized as locked.
26
27 public:
29 void reset() {
30 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
31 m_count = 0;
32 }
33
35 void notify() {
36 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
37 ++m_count;
38 m_condition.notify_one();
39 }
40
42 void wait() {
43 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
44 while (!m_count) // Handle spurious wake-ups.
45 m_condition.wait(lock);
46 --m_count;
47 }
48
50 bool wait_for(std::chrono::milliseconds timeout_ms) {
51 std::cv_status l_Stat = std::cv_status::no_timeout;
52 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
53 while (!m_count && l_Stat == std::cv_status::no_timeout) // Handle spurious wake-ups.
54 l_Stat = m_condition.wait_for(lock, timeout_ms);
55 if (l_Stat == std::cv_status::no_timeout)
56 --m_count;
57 return (l_Stat == std::cv_status::no_timeout);
58 }
59
61 bool try_wait() {
62 std::unique_lock<decltype(m_mutex)> lock(m_mutex);
63 if (m_count) {
64 --m_count;
65 return true;
66 }
67 return false;
68 }
69 };
70
71 template <typename MsgT>
73 {
74 private:
75 std::queue<MsgT> m_MsgQ;
76 std::mutex m_Lock;
77 CSemaphore m_Sem;
78
79 public:
80 bool empty()
81 {
82 m_Lock.lock();
83 bool l_em = m_MsgQ.empty();
84 m_Lock.unlock();
85 return l_em;
86 }
87 void clear()
88 {
89 m_Lock.lock();
90 std::queue<MsgT> l_Empty;
91 std::swap(m_MsgQ, l_Empty);
92 m_Sem.reset();
93 m_Lock.unlock();
94 }
95 void push(MsgT pMsg)
96 {
97 m_Lock.lock();
98 m_MsgQ.push(pMsg);
99 m_Sem.notify();
100 m_Lock.unlock();
101 }
102 void pop(MsgT & rV)
103 {
104 m_Sem.wait();
105 m_Lock.lock();
106 if (m_MsgQ.empty())
107 return;
108 rV = m_MsgQ.front();
109 m_MsgQ.pop();
110 m_Lock.unlock();
111 }
112 bool try_pop(MsgT & rV)
113 {
114 bool l_Success = false;
115 m_Lock.lock();
116 if (m_Sem.try_wait())
117 {
118 l_Success = true;
119 rV = m_MsgQ.front();
120 m_MsgQ.pop();
121 }
122 m_Lock.unlock();
123 return l_Success;
124 }
125 };
126
127 class CTimer
128 {
129 private:
130 std::thread m_Thread; // Thread object
131 std::mutex m_Lock; // Lock onto public interface
132 std::chrono::milliseconds m_Period_ms;
133 bool m_SingleShot;
134 CSemaphore m_AbortSem;
135 std::function<void(void)> m_NotifyEvent;
136
137 //-----------------------------------------//
138 // Thread Context
139 //-----------------------------------------//
140 public:
141 // Constructor as: CTimer timer(Function)
142 CTimer(const std::function<void(void)> & rTimerEventNotifierFunction)
143 : m_NotifyEvent(rTimerEventNotifierFunction)
144 {}
145 // Constructor as: CTimer timer(&Class::method, &ClassObj)
146 template<class Fn, class... Args>
147 CTimer(Fn&& rTimerEventNotifierFunction, Args&&... Ax)
148 : m_NotifyEvent(std::bind(rTimerEventNotifierFunction, Ax...))
149 {}
150 virtual ~CTimer()
151 {
152 Stop();
153 }
154 private:
155 void ThreadMain()
156 {
157 while (1)
158 {
159 // Wait for timer period to elapse
160 bool l_Aborted = m_AbortSem.wait_for(m_Period_ms);
161
162 // If requested to abort, quit the thread without notification
163 if (l_Aborted)
164 return;
165
166 // Notify event
167 m_NotifyEvent();
168
169 // Check if we continue
170 if (m_SingleShot)
171 return; // If single shot, stop thread
172 }
173 }
174 //-----------------------------------------//
175 // Caller Context
176 //-----------------------------------------//
177 public:
178 bool StartSingleShot(std::chrono::milliseconds Delay_ms)
179 {
180 std::lock_guard<decltype(m_Lock)> l_lg(m_Lock);
181
182 if (m_Thread.joinable()) // If thread is already running
183 return false;
184
185 m_SingleShot = true;
186 m_Period_ms = Delay_ms;
187 m_AbortSem.reset();
188 m_Thread = std::thread(&CTimer::ThreadMain, this);
189 return true;
190 }
191 bool Start(std::chrono::milliseconds Period_ms)
192 {
193 std::lock_guard<decltype(m_Lock)> l_lg(m_Lock);
194
195 if (m_Thread.joinable()) // If thread is already running
196 return false;
197
198 m_SingleShot = false;
199 m_Period_ms = Period_ms;
200 m_AbortSem.reset();
201 m_Thread = std::thread(&CTimer::ThreadMain, this);
202 return true;
203 }
204 void Stop()
205 {
206 std::lock_guard<decltype(m_Lock)> l_lg(m_Lock);
207
208 if (m_Thread.joinable()) // If worker thread is running
209 {
210 m_AbortSem.notify(); // Notify thread to stop
211 m_Thread.join(); // Wait for worker thread (and its timer thread) to be stopped
212 }
213 }
214 };
215
216
217 //-----------------------------------------//
218 //-----------------------------------------//
219 // Class
220 //-----------------------------------------//
221 //-----------------------------------------//
222 template <typename UserMsgT>
224 {
225 //-----------------------------------------//
226 // Types
227 //-----------------------------------------//
228 protected:
230 private:
231 struct sMailBoxMsg {
232 eEventType Evt;
233 UserMsgT UserMsg;
234 sMailBoxMsg()
235 {}
236 sMailBoxMsg(eEventType EvtType, const UserMsgT & rMsg)
237 : Evt(EvtType), UserMsg(rMsg)
238 {}
239 sMailBoxMsg(eEventType EvtType)
240 : Evt(EvtType)
241 {}
242 };
243 protected:
244 //-----------------------------------------//
245 // Attributes
246 //-----------------------------------------//
247 private:
248 CMailBox<sMailBoxMsg> m_MailBox;
249 std::thread m_Thread;
250 std::atomic<bool> m_RequestedToStop;
251
252 //-----------------------------------------//
253 // Caller context
254 //-----------------------------------------//
255 protected:
256 void l_SendMsg(const UserMsgT & rMsg);
257 public:
259 : m_RequestedToStop(false)
260 {}
263 protected:
265 //-----------------------------------------//
266 // Worker Thread context
267 //-----------------------------------------//
268 private:
269 void l_ThreadMain();
270 protected:
271 virtual void l_ThreadTask(eEventType EvtType, UserMsgT * pMsg) = 0;
272 };
273
274
275 //-----------------------------------------//
276 //-----------------------------------------//
277 // Implementation
278 //-----------------------------------------//
279 //-----------------------------------------//
280 template <typename UserMsgT>
282 {
283 if (!m_Thread.joinable()) // If thread is not already running
284 {
285 m_MailBox.clear();
286 m_RequestedToStop = false;
287 m_Thread = std::thread(&CThreadedMailBox::l_ThreadMain, this);
288 }
289 }
290
291 template <typename UserMsgT>
293 {
294 m_RequestedToStop = true;
295 m_MailBox.push(sMailBoxMsg(eEventType::kExit)); // Request worker thread to stop
296 if (m_Thread.joinable() && std::this_thread::get_id() != m_Thread.get_id()) // If worker thread is running
297 m_Thread.join(); // Wait for worker thread to be stopped
298 }
299
300 template <typename UserMsgT>
301 void CThreadedMailBox<UserMsgT>::l_SendMsg(const UserMsgT & rMsg)
302 {
303 m_MailBox.push(sMailBoxMsg(eEventType::kUserMsg, rMsg)); // Push our copy to our message queue
304 }
305
306 template <typename UserMsgT>
308 {
309 return m_RequestedToStop;
310 }
311
312 template <typename UserMsgT>
313 void CThreadedMailBox<UserMsgT>::l_ThreadMain()
314 {
315 sMailBoxMsg Msg;
316 bool l_RunWorkerThread = true;
317 while (l_RunWorkerThread)
318 {
319 m_MailBox.pop(Msg);
320 switch (Msg.Evt)
321 {
322 case eEventType::kExit:
323 l_RunWorkerThread = false; // Request this thread to stop
324 l_ThreadTask(Msg.Evt, nullptr); // Call thread task for the last time
325 break;
326 case eEventType::kUserMsg:
327 l_ThreadTask(Msg.Evt, &Msg.UserMsg); // Forward user message
328 break;
329 }
330 }
331 }
332
333 } // namespace ThreadedMailbox
334} // namespace MTL
void reset()
Reset semaphore object.
bool wait_for(std::chrono::milliseconds timeout_ms)
Wait for a semaphore for a limited time.
void notify()
Raise a semaphore.
bool try_wait()
Check whether a semaphore has been raised.
void wait()
Wait for a semaphore.
CTimer(const std::function< void(void)> &rTimerEventNotifierFunction)
bool Start(std::chrono::milliseconds Period_ms)
bool StartSingleShot(std::chrono::milliseconds Delay_ms)
CTimer(Fn &&rTimerEventNotifierFunction, Args &&... Ax)
virtual void l_ThreadTask(eEventType EvtType, UserMsgT *pMsg)=0
void l_SendMsg(const UserMsgT &rMsg)