1 | // |
---|---|
2 | // Event.cpp |
3 | // |
4 | // Library: Foundation |
5 | // Package: Threading |
6 | // Module: Event |
7 | // |
8 | // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. |
9 | // and Contributors. |
10 | // |
11 | // SPDX-License-Identifier: BSL-1.0 |
12 | // |
13 | |
14 | |
15 | #include "Poco/Event.h" |
16 | |
17 | |
18 | namespace Poco { |
19 | |
20 | |
21 | Event::Event(EventType type): _state(false), |
22 | _autoreset(type == EVENT_AUTORESET) |
23 | { |
24 | } |
25 | |
26 | |
27 | Event::Event(bool autoReset): _state(false), |
28 | _autoreset(autoReset) |
29 | { |
30 | } |
31 | |
32 | |
33 | Event::~Event() |
34 | { |
35 | } |
36 | |
37 | |
38 | void Event::set() |
39 | { |
40 | try |
41 | { |
42 | std::lock_guard<std::mutex> lock(_mutex); |
43 | _state = true; |
44 | if (_autoreset) _cond.notify_one(); |
45 | else _cond.notify_all(); |
46 | } |
47 | catch (std::system_error &e) |
48 | { |
49 | throw SystemException(e.what()); |
50 | } |
51 | } |
52 | |
53 | |
54 | void Event::reset() |
55 | { |
56 | try |
57 | { |
58 | std::lock_guard<std::mutex> lock(_mutex); |
59 | _state = false; |
60 | } |
61 | catch (std::system_error &e) |
62 | { |
63 | throw SystemException(e.what()); |
64 | } |
65 | } |
66 | |
67 | |
68 | void Event::wait() |
69 | { |
70 | try |
71 | { |
72 | std::unique_lock<std::mutex> lock(_mutex); |
73 | while (!_state) |
74 | _cond.wait(lock, [this]() { return this->_state.load(); }); |
75 | if (_autoreset) _state = false; |
76 | } |
77 | catch (std::system_error &e) |
78 | { |
79 | throw SystemException(e.what()); |
80 | } |
81 | } |
82 | |
83 | |
84 | bool Event::waitImpl(long milliseconds) |
85 | { |
86 | try |
87 | { |
88 | std::unique_lock<std::mutex> lock(_mutex); |
89 | bool ret = _cond.wait_for(lock, std::chrono::milliseconds(milliseconds), [this]() { return this->_state.load(); }); |
90 | if (ret && _autoreset) _state = false; |
91 | return ret; |
92 | } |
93 | catch (std::system_error &e) |
94 | { |
95 | throw SystemException(e.what()); |
96 | } |
97 | } |
98 | |
99 | |
100 | } // namespace Poco |
101 |