source: src/Actions/ActionQueue.cpp@ 419fa2

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

tempcommit: Fixing access to clearQueue() which deadlocked before.

  • Property mode set to 100644
File size: 11.9 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 <iterator>
47#include <string>
48#include <sstream>
49#include <vector>
50
51#include "Actions/ActionExceptions.hpp"
52#include "Actions/ActionHistory.hpp"
53#include "Actions/ActionRegistry.hpp"
54#include "World.hpp"
55
56using namespace MoleCuilder;
57
58const Action* ActionQueue::_lastchangedaction = NULL;
59
60ActionQueue::ActionQueue() :
61 Observable("ActionQueue"),
62 AR(new ActionRegistry()),
63 history(new ActionHistory),
64#ifndef HAVE_ACTION_THREAD
65 lastActionOk(true)
66#else
67 lastActionOk(true),
68 CurrentAction(0),
69 run_thread_isIdle(true),
70 run_thread_running(false),
71 run_thread(boost::bind(&ActionQueue::run, this))
72#endif
73{
74 // channels of observable
75 Channels *OurChannel = new Channels;
76 NotificationChannels.insert( std::make_pair(static_cast<Observable *>(this), OurChannel) );
77 // add instance for each notification type
78 for (size_t type = 0; type < NotificationType_MAX; ++type)
79 OurChannel->addChannel(type);
80}
81
82ActionQueue::~ActionQueue()
83{
84#ifdef HAVE_ACTION_THREAD
85 stop();
86
87 clearTempQueue();
88#endif
89
90 clearQueue();
91
92 delete history;
93 delete AR;
94}
95
96void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
97{
98 const Action * const registryaction = AR->getActionByName(name);
99 queueAction(registryaction, state);
100}
101
102void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
103{
104 Action *newaction = _action->clone(state);
105 newaction->prepare(state);
106#ifdef HAVE_ACTION_THREAD
107 mtx_actionqueue.lock();
108#endif
109 actionqueue.push_back( newaction );
110#ifndef HAVE_ACTION_THREAD
111 try {
112 newaction->call();
113 lastActionOk = true;
114 } catch(ActionFailureException &e) {
115 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
116 World::getInstance().setExitFlag(5);
117// clearQueue(actionqueue.size()-1);
118 lastActionOk = false;
119// std::cerr << "Remaining Actions cleared from queue." << std::endl;
120 } catch (std::exception &e) {
121 pushStatus("FAIL: General exception caught, aborting.");
122 World::getInstance().setExitFlag(134);
123// clearQueue(actionqueue.size()-1);
124 lastActionOk = false;
125// std::cerr << "Remaining Actions cleared from queue." << std::endl;
126 }
127 if (lastActionOk) {
128 OBSERVE;
129 NOTIFY(ActionQueued);
130 _lastchangedaction = newaction;
131 }
132#else
133 mtx_actionqueue.unlock();
134 const bool new_run_thread_isIdle = isActionQueueDone();
135 setrun_thread_isIdle(new_run_thread_isIdle);
136#endif
137}
138
139#ifdef HAVE_ACTION_THREAD
140bool ActionQueue::isActionQueueDone() const
141{
142 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
143 return (CurrentAction == actionqueue.size());
144}
145
146bool ActionQueue::isTempQueueDone() const
147{
148 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
149 return tempqueue.empty();
150}
151#endif
152
153void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
154{
155#ifndef HAVE_ACTION_THREAD
156 queueAction(_action, state);
157#else
158 Action *newaction = _action->clone(state);
159 newaction->prepare(state);
160 {
161 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
162 tempqueue.push_back( newaction );
163 }
164 {
165 bool new_run_thread_isIdle = getrun_thread_isIdle();
166 new_run_thread_isIdle &= isTempQueueDone();
167 setrun_thread_isIdle(new_run_thread_isIdle);
168 }
169#endif
170}
171
172#ifdef HAVE_ACTION_THREAD
173void ActionQueue::run()
174{
175 {
176 boost::lock_guard<boost::mutex> lock(mtx_run_thread_isIdle);
177 run_thread_running = true;
178 }
179 bool Interrupted = false;
180 do {
181 // sleep for some time and wait for queue to fill up again
182 try {
183#if BOOST_VERSION < 105000
184 boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
185#else
186 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
187#endif
188 } catch(boost::thread_interrupted &e) {
189 LOG(2, "INFO: ActionQueue has received stop signal.");
190 Interrupted = true;
191 }
192// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
193 // call all currently present Actions
194 insertTempQueue();
195 while ((!Interrupted) && (!isActionQueueDone())) {
196 // boost::this_thread::disable_interruption di;
197 // access actionqueue, hence using mutex
198 mtx_actionqueue.lock();
199 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
200 try {
201 actionqueue[CurrentAction]->call();
202 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
203 lastActionOk = true;
204 } catch(ActionFailureException &e) {
205 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
206 World::getInstance().setExitFlag(5);
207 lastActionOk = false;
208 std::cerr << "Remaining Actions cleared from queue." << std::endl;
209 } catch (std::exception &e) {
210 pushStatus("FAIL: General exception caught, aborting.");
211 World::getInstance().setExitFlag(134);
212 std::cerr << "Remaining Actions cleared from queue." << std::endl;
213 }
214 // remember action we juse executed
215 const Action *lastaction = actionqueue[CurrentAction];
216 // step on to next action and check for end
217 if (lastActionOk)
218 CurrentAction++;
219 // insert new actions (before [CurrentAction]) if they have been spawned
220 // we must have an extra vector for this, as we cannot change actionqueue
221 // while an action instance is "in-use"
222 mtx_actionqueue.unlock();
223
224 if (!lastActionOk) {
225 clearQueue(CurrentAction);
226 clearTempQueue();
227 }
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
252void ActionQueue::insertTempQueue()
253{
254 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
255 if (!tempqueue.empty()) {
256 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
257 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
258 std::advance(InsertionIter, CurrentAction);
259 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
260 tempqueue.clear();
261 }
262}
263
264void ActionQueue::setrun_thread_isIdle(
265 const bool _run_thread_isIdle)
266{
267 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
268 run_thread_isIdle = _run_thread_isIdle;
269}
270
271bool ActionQueue::getrun_thread_isIdle() const
272{
273 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
274 return run_thread_isIdle;
275}
276
277void ActionQueue::wait()
278{
279 if (run_thread_running) {
280 boost::unique_lock<boost::mutex> lock(mtx_run_thread_isIdle);
281 while(!run_thread_isIdle)
282 {
283 cond_idle.wait(lock);
284 }
285 }
286}
287
288void ActionQueue::stop()
289{
290 // notify actionqueue thread that we wish to terminate
291 run_thread.interrupt();
292 // wait till it ends
293 run_thread.join();
294}
295#endif
296
297Action* ActionQueue::getActionByName(const std::string &name)
298{
299 return AR->getActionByName(name);
300}
301
302bool ActionQueue::isActionKnownByName(const std::string &name) const
303{
304 return AR->isActionPresentByName(name);
305}
306
307void ActionQueue::registerAction(Action *_action)
308{
309 AR->registerInstance(_action);
310}
311
312void ActionQueue::outputAsCLI(std::ostream &output) const
313{
314 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
315 iter != actionqueue.end();
316 ++iter) {
317 // skip store-session in printed list
318 if ( ((*iter)->getName() != std::string("store-session"))
319 && ((*iter)->getName() != std::string("load-session"))) {
320 if (iter != actionqueue.begin())
321 output << " ";
322 (*iter)->outputAsCLI(output);
323 }
324 }
325 output << std::endl;
326}
327
328void ActionQueue::outputAsPython(std::ostream &output) const
329{
330 const std::string prefix("pyMoleCuilder");
331 output << "import " << prefix << std::endl;
332 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
333 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
334 iter != actionqueue.end();
335 ++iter) {
336 // skip store-session in printed list
337 if ( ((*iter)->getName() != std::string("store-session"))
338 && ((*iter)->getName() != std::string("load-session")))
339 (*iter)->outputAsPython(output, prefix);
340 }
341 output << "# =========================== Stored Session END ===========================" << std::endl;
342}
343
344const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
345{
346 // this const_cast is just required as long as we have a non-const getActionByName
347 const Action * const action = const_cast<ActionQueue *>(this)->getActionByName(name);
348 return action->Traits;
349}
350
351void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
352{
353 history->addElement(_Action, _state);
354}
355
356void ActionQueue::clear()
357{
358 history->clear();
359}
360
361void ActionQueue::clearQueue(const size_t _fromAction)
362{
363 // free all actions contained in actionqueue
364 {
365#ifdef HAVE_ACTION_THREAD
366 boost::lock_guard<boost::mutex> lock(mtx_actionqueue);
367#endif
368 LOG(1, "Removing all Actions from position " << _fromAction << " onward.");
369 // free all actions still to be called contained in actionqueue
370 ActionQueue_t::iterator inititer = actionqueue.begin();
371 std::advance(inititer, _fromAction);
372 for (ActionQueue_t::iterator iter = inititer; iter != actionqueue.end(); ++iter)
373 delete *iter;
374 actionqueue.erase(inititer, actionqueue.end());
375 LOG(1, "There are " << actionqueue.size() << " remaining Actions.");
376#ifdef HAVE_ACTION_THREAD
377 CurrentAction = actionqueue.size();
378#endif
379 }
380}
381
382#ifdef HAVE_ACTION_THREAD
383void ActionQueue::clearTempQueue()
384{
385 // free all actions contained in tempqueue
386 {
387 boost::lock_guard<boost::mutex> lock(mtx_tempqueue);
388 for (ActionQueue_t::iterator iter = tempqueue.begin();
389 !tempqueue.empty(); iter = tempqueue.begin()) {
390 delete *iter;
391 tempqueue.erase(iter);
392 }
393 }
394}
395#endif
396
397const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
398{
399 ActionTokens_t returnlist;
400
401 returnlist.insert(
402 returnlist.end(),
403 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
404 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
405
406 return returnlist;
407}
408
409void ActionQueue::undoLast()
410{
411 history->undoLast();
412}
413
414bool ActionQueue::canUndo() const
415{
416 return history->hasUndo();
417}
418
419void ActionQueue::redoLast()
420{
421 history->redoLast();
422}
423
424bool ActionQueue::canRedo() const
425{
426 return history->hasRedo();
427}
428
429
430CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.