PLCnext API Documentation 23.6.0.37
AutoResetEvent.hpp
1
2//
3// Copyright PHOENIX CONTACT Electronics GmbH
4//
6#pragma once
8
9#include <boost/thread/locks.hpp>
10#include <boost/interprocess/sync/interprocess_mutex.hpp>
11#include <boost/interprocess/sync/interprocess_condition.hpp>
12
13#include <mutex>
14#include <thread>
15#include <memory>
16
17
18namespace Arp { namespace System { namespace Commons { namespace Ipc
19{
20
24{
25public: // typedefs
27 typedef std::shared_ptr<AutoResetEvent> Ptr;
28
29public:
32 explicit AutoResetEvent(bool initial = false);
33
36 void Set(void);
37
39 void Reset(void);
40
45 bool WaitOne(unsigned long timeoutMs = 0);
46
47private: // methods.
48 bool WaitOneInfinite(void);
49 bool TimedWaitOne(unsigned long timeoutMs);
50
51private: // deleted methods
52 AutoResetEvent(const AutoResetEvent&) = delete;
53 AutoResetEvent& operator=(const AutoResetEvent&) = delete;
54
55private: // fields.
56 bool flag;
57 boost::interprocess::interprocess_mutex syncRoot;
58 boost::interprocess::interprocess_condition signal;
59};
60
62// inline methods of class AutoResetEvent
64 : flag(initial)
65{
66}
67
69{
70 boost::lock_guard<boost::interprocess::interprocess_mutex> lock(this->syncRoot);
71 this->flag = true;
72 this->signal.notify_one();
73}
74
76{
77 boost::lock_guard<boost::interprocess::interprocess_mutex> lock(this->syncRoot);
78 this->flag = false;
79}
80
81inline bool AutoResetEvent::WaitOne(unsigned long timeoutMs)
82{
83 return (timeoutMs == 0) ? WaitOneInfinite() : TimedWaitOne(timeoutMs);
84}
85
86inline bool AutoResetEvent::WaitOneInfinite()
87{
88 boost::unique_lock<boost::interprocess::interprocess_mutex> lock(this->syncRoot);
89 while (!this->flag) // prevent spurious wakeups from doing harm (OR: is really necessary, see https://en.wikipedia.org/wiki/Spurious_wakeup)
90 {
91 this->signal.wait(lock);
92 }
93 this->flag = false; // WaitOne auto-resets this flag
94 return true;
95}
96
97}}}} // end of namespace Arp::System::Commons::Threading
Ipc-ready variant of Arp::System::Commons::Threading::AutoResetEvent
Definition: AutoResetEvent.hpp:24
std::shared_ptr< AutoResetEvent > Ptr
Definition of a pointer in the contet of an AutoResetEvent.
Definition: AutoResetEvent.hpp:27
AutoResetEvent(bool initial=false)
Creates a new object with specified initial state.
Definition: AutoResetEvent.hpp:63
void Set(void)
Sets the event to signaled state.
Definition: AutoResetEvent.hpp:68
bool WaitOne(unsigned long timeoutMs=0)
Suspends thread execution until event is signaled by another thread.
Definition: AutoResetEvent.hpp:81
void Reset(void)
Resets the event state to non-signaled.
Definition: AutoResetEvent.hpp:75
Root namespace for the PLCnext API