1 | // |
---|---|
2 | // ActiveDispatcher.cpp |
3 | // |
4 | // Library: Foundation |
5 | // Package: Threading |
6 | // Module: ActiveObjects |
7 | // |
8 | // Copyright (c) 2006-2007, Applied Informatics Software Engineering GmbH. |
9 | // and Contributors. |
10 | // |
11 | // SPDX-License-Identifier: BSL-1.0 |
12 | // |
13 | |
14 | |
15 | #include "Poco/ActiveDispatcher.h" |
16 | #include "Poco/Notification.h" |
17 | #include "Poco/AutoPtr.h" |
18 | |
19 | |
20 | namespace Poco { |
21 | |
22 | |
23 | namespace |
24 | { |
25 | class MethodNotification: public Notification |
26 | { |
27 | public: |
28 | MethodNotification(ActiveRunnableBase::Ptr pRunnable): |
29 | _pRunnable(pRunnable) |
30 | { |
31 | } |
32 | |
33 | ActiveRunnableBase::Ptr runnable() const |
34 | { |
35 | return _pRunnable; |
36 | } |
37 | |
38 | private: |
39 | ActiveRunnableBase::Ptr _pRunnable; |
40 | }; |
41 | |
42 | class StopNotification: public Notification |
43 | { |
44 | }; |
45 | } |
46 | |
47 | |
48 | ActiveDispatcher::ActiveDispatcher() |
49 | { |
50 | _thread.start(*this); |
51 | } |
52 | |
53 | |
54 | ActiveDispatcher::ActiveDispatcher(Thread::Priority prio) |
55 | { |
56 | _thread.setPriority(prio); |
57 | _thread.start(*this); |
58 | } |
59 | |
60 | |
61 | ActiveDispatcher::~ActiveDispatcher() |
62 | { |
63 | try |
64 | { |
65 | stop(); |
66 | } |
67 | catch (...) |
68 | { |
69 | } |
70 | } |
71 | |
72 | |
73 | void ActiveDispatcher::start(ActiveRunnableBase::Ptr pRunnable) |
74 | { |
75 | poco_check_ptr (pRunnable); |
76 | |
77 | _queue.enqueueNotification(new MethodNotification(pRunnable)); |
78 | } |
79 | |
80 | |
81 | void ActiveDispatcher::cancel() |
82 | { |
83 | _queue.clear(); |
84 | } |
85 | |
86 | |
87 | void ActiveDispatcher::run() |
88 | { |
89 | AutoPtr<Notification> pNf = _queue.waitDequeueNotification(); |
90 | while (pNf && !dynamic_cast<StopNotification*>(pNf.get())) |
91 | { |
92 | MethodNotification* pMethodNf = dynamic_cast<MethodNotification*>(pNf.get()); |
93 | poco_check_ptr (pMethodNf); |
94 | ActiveRunnableBase::Ptr pRunnable = pMethodNf->runnable(); |
95 | pRunnable->duplicate(); // run will release |
96 | pRunnable->run(); |
97 | pRunnable = 0; |
98 | pNf = 0; |
99 | pNf = _queue.waitDequeueNotification(); |
100 | } |
101 | } |
102 | |
103 | |
104 | void ActiveDispatcher::stop() |
105 | { |
106 | _queue.clear(); |
107 | _queue.wakeUpAll(); |
108 | _queue.enqueueNotification(new StopNotification); |
109 | _thread.join(); |
110 | } |
111 | |
112 | |
113 | } // namespace Poco |
114 |