source: src/Actions/ActionQueue.cpp@ fff8fc

Last change on this file since fff8fc was fff8fc, checked in by Frederik Heber <heber@…>, 10 years ago

Cleaned up use of mutexes in ActionQueue.

  • tempqueue now has its own mutex.
  • more often using lock_guard.
  • run_thread_isIdle has own mutex.
  • Property mode set to 100644
File size: 11.6 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 Frederik Heber. All rights reserved.
5 *
6 *
7 * This file is part of MoleCuilder.
8 *
9 * MoleCuilder is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * MoleCuilder is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24 * ActionQueue.cpp
25 *
26 * Created on: Aug 16, 2013
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include "Actions/ActionQueue.hpp"
38
39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
41#include "CodePatterns/Log.hpp"
42#include "CodePatterns/Singleton_impl.hpp"
43
44#include <boost/date_time/posix_time/posix_time.hpp>
45#include <boost/version.hpp>
46#include <string>
47#include <sstream>
48#include <vector>
49
50#include "Actions/ActionExceptions.hpp"
51#include "Actions/ActionHistory.hpp"
52#include "Actions/ActionRegistry.hpp"
53#include "World.hpp"
54
55using namespace MoleCuilder;
56
57const Action* ActionQueue::_lastchangedaction = NULL;
58
59ActionQueue::ActionQueue() :
60 Observable("ActionQueue"),
61 AR(new ActionRegistry()),
62 history(new ActionHistory),
63 CurrentAction(0),
64#ifndef HAVE_ACTION_THREAD
65 lastActionOk(true)
66#else
67 lastActionOk(true),
68 run_thread_isIdle(true),
69 run_thread_running(false),
70 run_thread(boost::bind(&ActionQueue::run, this))
71#endif
72{
73 // channels of observable
74 Channels *OurChannel = new Channels;
75 NotificationChannels.insert( std::make_pair(static_cast<Observable *>(this), OurChannel) );
76 // add instance for each notification type
77 for (size_t type = 0; type < NotificationType_MAX; ++type)
78 OurChannel->addChannel(type);
79}
80
81ActionQueue::~ActionQueue()
82{
83#ifdef HAVE_ACTION_THREAD
84 stop();
85#endif
86
87 clearQueue();
88
89 delete history;
90 delete AR;
91}
92
93void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
94{
95 const Action * const registryaction = AR->getActionByName(name);
96 queueAction(registryaction, state);
97}
98
99void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
100{
101 Action *newaction = _action->clone(state);
102 newaction->prepare(state);
103#ifdef HAVE_ACTION_THREAD
104 mtx_actionqueue.lock();
105#endif
106 actionqueue.push_back( newaction );
107#ifndef HAVE_ACTION_THREAD
108 try {
109 newaction->call();
110 lastActionOk = true;
111 } catch(ActionFailureException &e) {
112 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
113 World::getInstance().setExitFlag(5);
114 clearQueue();
115 lastActionOk = false;
116 std::cerr << "ActionQueue cleared." << std::endl;
117 } catch (std::exception &e) {
118 pushStatus("FAIL: General exception caught, aborting.");
119 World::getInstance().setExitFlag(134);
120 clearQueue();
121 lastActionOk = false;
122 std::cerr << "ActionQueue cleared." << std::endl;
123 }
124 if (lastActionOk) {
125 OBSERVE;
126 NOTIFY(ActionQueued);
127 _lastchangedaction = newaction;
128 }
129#else
130 const bool new_run_thread_isIdle = (CurrentAction == actionqueue.size());
131 mtx_actionqueue.unlock();
132 {
133 boost::lock_guard<boost::mutex> lock(mtx_run_thread_isIdle);
134 run_thread_isIdle = new_run_thread_isIdle;
135 }
136#endif
137}
138
139bool ActionQueue::isActionQueueDone() const
140{
141#ifdef HAVE_ACTION_THREAD
142 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
143#endif
144 return (CurrentAction == actionqueue.size());
145}
146
147bool ActionQueue::isTempQueueDone() const
148{
149#ifdef HAVE_ACTION_THREAD
150 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
151#endif
152 return tempqueue.empty();
153}
154
155void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
156{
157#ifndef HAVE_ACTION_THREAD
158 queueAction(_action, state);
159#else
160 Action *newaction = _action->clone(state);
161 newaction->prepare(state);
162 {
163 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
164 tempqueue.push_back( newaction );
165 }
166 {
167 bool new_run_thread_isIdle = getrun_thread_isIdle();
168 new_run_thread_isIdle &= isTempQueueDone();
169 setrun_thread_isIdle(new_run_thread_isIdle);
170 }
171#endif
172}
173
174#ifdef HAVE_ACTION_THREAD
175void ActionQueue::run()
176{
177 {
178 boost::lock_guard<boost::mutex> lock(mtx_run_thread_isIdle);
179 run_thread_running = true;
180 }
181 bool Interrupted = false;
182 do {
183 // sleep for some time and wait for queue to fill up again
184 try {
185#if BOOST_VERSION < 105000
186 boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
187#else
188 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
189#endif
190 } catch(boost::thread_interrupted &e) {
191 LOG(2, "INFO: ActionQueue has received stop signal.");
192 Interrupted = true;
193 }
194// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
195 // call all currently present Actions
196 insertTempQueue();
197 while ((!Interrupted) && (!isActionQueueDone())) {
198 // boost::this_thread::disable_interruption di;
199 // access actionqueue, hence using mutex
200 mtx_actionqueue.lock();
201 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
202 try {
203 actionqueue[CurrentAction]->call();
204 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
205 lastActionOk = true;
206 } catch(ActionFailureException &e) {
207 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
208 World::getInstance().setExitFlag(5);
209 clearQueue();
210 lastActionOk = false;
211 std::cerr << "ActionQueue cleared." << std::endl;
212 CurrentAction = (size_t)-1;
213 } catch (std::exception &e) {
214 pushStatus("FAIL: General exception caught, aborting.");
215 World::getInstance().setExitFlag(134);
216 clearQueue();
217 std::cerr << "ActionQueue cleared." << std::endl;
218 CurrentAction = (size_t)-1;
219 }
220 // remember action we juse executed
221 const Action *lastaction = actionqueue[CurrentAction];
222 // step on to next action and check for end
223 CurrentAction++;
224 // insert new actions (before [CurrentAction]) if they have been spawned
225 // we must have an extra vector for this, as we cannot change actionqueue
226 // while an action instance is "in-use"
227 mtx_actionqueue.unlock();
228
229 insertTempQueue();
230
231 // set last action
232 if (lastActionOk) {
233 OBSERVE;
234 NOTIFY(ActionQueued);
235 _lastchangedaction = lastaction;
236 }
237 }
238 {
239 bool new_run_thread_isIdle = isActionQueueDone();
240 new_run_thread_isIdle &= isTempQueueDone();
241 setrun_thread_isIdle(new_run_thread_isIdle);
242 }
243 cond_idle.notify_one();
244// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
245 } while (!Interrupted);
246 {
247 boost::lock_guard<boost::mutex> lock(mtx_run_thread_isIdle);
248 run_thread_running = false;
249 }
250}
251#endif
252
253void ActionQueue::insertTempQueue()
254{
255#ifdef HAVE_ACTION_THREAD
256 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
257#endif
258 if (!tempqueue.empty()) {
259#ifdef HAVE_ACTION_THREAD
260 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
261#endif
262 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
263 std::advance(InsertionIter, CurrentAction);
264 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
265 tempqueue.clear();
266 }
267}
268
269#ifdef HAVE_ACTION_THREAD
270void ActionQueue::setrun_thread_isIdle(
271 const bool _run_thread_isIdle)
272{
273 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
274 run_thread_isIdle = _run_thread_isIdle;
275}
276
277bool ActionQueue::getrun_thread_isIdle() const
278{
279 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
280 return run_thread_isIdle;
281}
282#endif
283
284#ifdef HAVE_ACTION_THREAD
285void ActionQueue::wait()
286{
287 if (run_thread_running) {
288 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
289 while(!run_thread_isIdle)
290 {
291 cond_idle.wait(lock);
292 }
293 }
294}
295#endif
296
297#ifdef HAVE_ACTION_THREAD
298void ActionQueue::stop()
299{
300 // notify actionqueue thread that we wish to terminate
301 run_thread.interrupt();
302 // wait till it ends
303 run_thread.join();
304}
305#endif
306
307Action* ActionQueue::getActionByName(const std::string &name)
308{
309 return AR->getActionByName(name);
310}
311
312bool ActionQueue::isActionKnownByName(const std::string &name) const
313{
314 return AR->isActionPresentByName(name);
315}
316
317void ActionQueue::registerAction(Action *_action)
318{
319 AR->registerInstance(_action);
320}
321
322void ActionQueue::outputAsCLI(std::ostream &output) const
323{
324 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
325 iter != actionqueue.end();
326 ++iter) {
327 // skip store-session in printed list
328 if ( ((*iter)->getName() != std::string("store-session"))
329 && ((*iter)->getName() != std::string("load-session"))) {
330 if (iter != actionqueue.begin())
331 output << " ";
332 (*iter)->outputAsCLI(output);
333 }
334 }
335 output << std::endl;
336}
337
338void ActionQueue::outputAsPython(std::ostream &output) const
339{
340 const std::string prefix("pyMoleCuilder");
341 output << "import " << prefix << std::endl;
342 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
343 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
344 iter != actionqueue.end();
345 ++iter) {
346 // skip store-session in printed list
347 if ( ((*iter)->getName() != std::string("store-session"))
348 && ((*iter)->getName() != std::string("load-session")))
349 (*iter)->outputAsPython(output, prefix);
350 }
351 output << "# =========================== Stored Session END ===========================" << std::endl;
352}
353
354const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
355{
356 // this const_cast is just required as long as we have a non-const getActionByName
357 const Action * const action = const_cast<ActionQueue *>(this)->getActionByName(name);
358 return action->Traits;
359}
360
361void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
362{
363 history->addElement(_Action, _state);
364}
365
366void ActionQueue::clear()
367{
368 history->clear();
369}
370
371void ActionQueue::clearQueue()
372{
373 // free all actions contained in actionqueue
374 {
375#ifdef HAVE_ACTION_THREAD
376 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
377#endif
378 for (ActionQueue_t::iterator iter = actionqueue.begin();
379 !actionqueue.empty(); iter = actionqueue.begin()) {
380 delete *iter;
381 actionqueue.erase(iter);
382 }
383 }
384 // free all actions contained in tempqueue
385 {
386#ifdef HAVE_ACTION_THREAD
387 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
388#endif
389 for (ActionQueue_t::iterator iter = tempqueue.begin();
390 !tempqueue.empty(); iter = tempqueue.begin()) {
391 delete *iter;
392 tempqueue.erase(iter);
393 }
394 }
395#ifdef HAVE_ACTION_THREAD
396 {
397 boost::unique_lock<boost::mutex> lock(mtx_idle);
398 run_thread_isIdle = true;
399 }
400#endif
401}
402
403const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
404{
405 ActionTokens_t returnlist;
406
407 returnlist.insert(
408 returnlist.end(),
409 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
410 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
411
412 return returnlist;
413}
414
415void ActionQueue::undoLast()
416{
417 history->undoLast();
418}
419
420void ActionQueue::redoLast()
421{
422 history->redoLast();
423}
424
425
426CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.