source: src/Actions/ActionQueue.cpp@ 7f1a1a

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 7f1a1a was 7f1a1a, checked in by Frederik Heber <heber@…>, 11 years ago

MEMFIX: ActionQueue would loose memory when action failed.

  • we cleared the queues and forget to delete contained Action instances.
  • Property mode set to 100644
File size: 8.9 KB
RevLine 
[628577]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
[1d3563]37#include "Actions/ActionQueue.hpp"
[628577]38
[690741]39#include "CodePatterns/Assert.hpp"
40#include "CodePatterns/IteratorAdaptors.hpp"
[46b181]41#include "CodePatterns/Log.hpp"
[628577]42#include "CodePatterns/Singleton_impl.hpp"
43
[415ddd]44#include <boost/date_time/posix_time/posix_time.hpp>
45#include <boost/version.hpp>
[46b181]46#include <string>
47#include <sstream>
[690741]48#include <vector>
49
[0d4168]50#include "Actions/ActionExceptions.hpp"
[6367dd]51#include "Actions/ActionHistory.hpp"
[ed3944]52#include "Actions/ActionRegistry.hpp"
[0d4168]53#include "World.hpp"
[ed3944]54
[628577]55using namespace MoleCuilder;
56
[ed3944]57ActionQueue::ActionQueue() :
[6367dd]58 AR(new ActionRegistry()),
[af5384]59 history(new ActionHistory),
[a61dbb]60 CurrentAction(0),
[74459a]61#ifndef HAVE_ACTION_THREAD
[a61dbb]62 lastActionOk(true)
[74459a]63#else
[a61dbb]64 lastActionOk(true),
[415ddd]65 run_thread(boost::bind(&ActionQueue::run, this)),
66 run_thread_isIdle(true)
[74459a]67#endif
[628577]68{}
69
70ActionQueue::~ActionQueue()
[ed3944]71{
[74459a]72#ifdef HAVE_ACTION_THREAD
[415ddd]73 stop();
[74459a]74#endif
[415ddd]75
[7f1a1a]76 clearQueue();
[af5384]77
[6367dd]78 delete history;
[ed3944]79 delete AR;
80}
[628577]81
[f54cda]82void ActionQueue::queueAction(const std::string &name, enum Action::QueryOptions state)
[05c989]83{
[7f1a1a]84 const Action * const registryaction = AR->getActionByName(name);
85 queueAction(registryaction, state);
[f54cda]86}
87
[7f1a1a]88void ActionQueue::queueAction(const Action * const _action, enum Action::QueryOptions state)
[f54cda]89{
[af5384]90 Action *newaction = _action->clone(state);
91 newaction->prepare(state);
[74459a]92#ifdef HAVE_ACTION_THREAD
[415ddd]93 mtx_queue.lock();
[74459a]94#endif
[7fc447]95 actionqueue.push_back( newaction );
[74459a]96#ifndef HAVE_ACTION_THREAD
97 try {
98 newaction->call();
[a61dbb]99 lastActionOk = true;
[74459a]100 } catch(ActionFailureException &e) {
101 std::cerr << "Action " << *boost::get_error_info<ActionNameString>(e) << " has failed." << std::endl;
102 World::getInstance().setExitFlag(5);
[7f1a1a]103 clearQueue();
[a61dbb]104 lastActionOk = false;
105 std::cerr << "ActionQueue cleared." << std::endl;
[74459a]106 }
107#else
[415ddd]108 {
109 boost::lock_guard<boost::mutex> lock(mtx_idle);
110 run_thread_isIdle = (CurrentAction == actionqueue.size());
[0d4168]111 }
[415ddd]112 mtx_queue.unlock();
[74459a]113#endif
[05c989]114}
115
[975b83]116void ActionQueue::insertAction(Action *_action, enum Action::QueryOptions state)
117{
[74459a]118#ifndef HAVE_ACTION_THREAD
119 queueAction(_action, state);
120#else
[415ddd]121 Action *newaction = _action->clone(state);
122 newaction->prepare(state);
123 mtx_queue.lock();
124 tempqueue.push_back( newaction );
125 {
126 boost::lock_guard<boost::mutex> lock(mtx_idle);
127 run_thread_isIdle = !((CurrentAction != actionqueue.size()) || !tempqueue.empty());
128 }
129 mtx_queue.unlock();
[74459a]130#endif
[415ddd]131}
132
[74459a]133#ifdef HAVE_ACTION_THREAD
[415ddd]134void ActionQueue::run()
135{
136 bool Interrupted = false;
137 do {
138 // sleep for some time and wait for queue to fill up again
139 try {
140#if BOOST_VERSION < 105000
141 run_thread.sleep(boost::get_system_time() + boost::posix_time::milliseconds(100));
142#else
[d93b4b3]143 boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
[415ddd]144#endif
145 } catch(boost::thread_interrupted &e) {
146 LOG(2, "INFO: ActionQueue has received stop signal.");
147 Interrupted = true;
148 }
149// LOG(1, "DEBUG: Start of ActionQueue's run() loop.");
150 // call all currently present Actions
151 mtx_queue.lock();
152 insertTempQueue();
153 bool status = (CurrentAction != actionqueue.size());
154 mtx_queue.unlock();
155 while (status) {
156 // boost::this_thread::disable_interruption di;
157 LOG(0, "Calling Action " << actionqueue[CurrentAction]->getName() << " ... ");
158 try {
159 actionqueue[CurrentAction]->call();
[0b6b77]160 pushStatus("SUCCESS: Action "+actionqueue[CurrentAction]->getName()+" successful.");
[a61dbb]161 lastActionOk = true;
[415ddd]162 } catch(ActionFailureException &e) {
[0b6b77]163 pushStatus("FAIL: Action "+*boost::get_error_info<ActionNameString>(e)+" has failed.");
[415ddd]164 World::getInstance().setExitFlag(5);
[7f1a1a]165 clearQueue();
[a61dbb]166 lastActionOk = false;
167 std::cerr << "ActionQueue cleared." << std::endl;
168 CurrentAction = (size_t)-1;
[415ddd]169 }
170 // access actionqueue, hence using mutex
171 mtx_queue.lock();
172 // step on to next action and check for end
173 CurrentAction++;
174 // insert new actions (before [CurrentAction]) if they have been spawned
175 // we must have an extra vector for this, as we cannot change actionqueue
176 // while an action instance is "in-use"
177 insertTempQueue();
178 status = (CurrentAction != actionqueue.size());
179 mtx_queue.unlock();
180 }
181 {
182 boost::lock_guard<boost::mutex> lock(mtx_idle);
183 run_thread_isIdle = !((CurrentAction != actionqueue.size()) || !tempqueue.empty());
184 }
185 cond_idle.notify_one();
186// LOG(1, "DEBUG: End of ActionQueue's run() loop.");
187 } while (!Interrupted);
188}
[74459a]189#endif
[415ddd]190
191void ActionQueue::insertTempQueue()
192{
193 if (!tempqueue.empty()) {
194 ActionQueue_t::iterator InsertionIter = actionqueue.begin();
195 std::advance(InsertionIter, CurrentAction);
196 actionqueue.insert( InsertionIter, tempqueue.begin(), tempqueue.end() );
197 tempqueue.clear();
198 }
199}
200
[74459a]201#ifdef HAVE_ACTION_THREAD
[415ddd]202void ActionQueue::wait()
203{
204 boost::unique_lock<boost::mutex> lock(mtx_idle);
205 while(!run_thread_isIdle)
206 {
207 cond_idle.wait(lock);
208 }
209}
[74459a]210#endif
[415ddd]211
[74459a]212#ifdef HAVE_ACTION_THREAD
[415ddd]213void ActionQueue::stop()
214{
215 // notify actionqueue thread that we wish to terminate
216 run_thread.interrupt();
217 // wait till it ends
218 run_thread.join();
[975b83]219}
[74459a]220#endif
[975b83]221
[a6ceab]222Action* ActionQueue::getActionByName(const std::string &name)
[1d3563]223{
[ed3944]224 return AR->getActionByName(name);
[1d3563]225}
226
[a6ceab]227bool ActionQueue::isActionKnownByName(const std::string &name) const
[1d3563]228{
[ed3944]229 return AR->isActionPresentByName(name);
[1d3563]230}
231
[126867]232void ActionQueue::registerAction(Action *_action)
233{
234 AR->registerInstance(_action);
235}
236
[46b181]237void ActionQueue::outputAsCLI(std::ostream &output) const
238{
[7fc447]239 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
240 iter != actionqueue.end();
[46b181]241 ++iter) {
[bad589]242 // skip store-session in printed list
[12d946]243 if ( ((*iter)->getName() != std::string("store-session"))
244 && ((*iter)->getName() != std::string("load-session"))) {
[7fc447]245 if (iter != actionqueue.begin())
[bad589]246 output << " ";
247 (*iter)->outputAsCLI(output);
248 }
[46b181]249 }
250 output << std::endl;
251}
252
[477012]253void ActionQueue::outputAsPython(std::ostream &output) const
254{
255 const std::string prefix("pyMoleCuilder");
256 output << "import " << prefix << std::endl;
[9e4655]257 output << "# ========================== Stored Session BEGIN ==========================" << std::endl;
[7fc447]258 for (ActionQueue_t::const_iterator iter = actionqueue.begin();
259 iter != actionqueue.end();
[477012]260 ++iter) {
261 // skip store-session in printed list
[12d946]262 if ( ((*iter)->getName() != std::string("store-session"))
263 && ((*iter)->getName() != std::string("load-session")))
[477012]264 (*iter)->outputAsPython(output, prefix);
265 }
[9e4655]266 output << "# =========================== Stored Session END ===========================" << std::endl;
[477012]267}
268
[a6ceab]269const ActionTrait& ActionQueue::getActionsTrait(const std::string &name) const
[690741]270{
271 // this const_cast is just required as long as we have a non-const getActionByName
272 const Action * const action = const_cast<ActionQueue *>(this)->getActionByName(name);
273 return action->Traits;
274}
275
[6367dd]276void ActionQueue::addElement(Action* _Action,ActionState::ptr _state)
277{
278 history->addElement(_Action, _state);
279}
280
281void ActionQueue::clear()
282{
283 history->clear();
284}
285
[7f1a1a]286void ActionQueue::clearQueue()
287{
288 // free all actions contained in actionqueue
289 for (ActionQueue_t::iterator iter = actionqueue.begin();
290 !actionqueue.empty(); iter = actionqueue.begin()) {
291 delete *iter;
292 actionqueue.erase(iter);
293 }
294 // free all actions contained in tempqueue
295 for (ActionQueue_t::iterator iter = tempqueue.begin();
296 !tempqueue.empty(); iter = tempqueue.begin()) {
297 delete *iter;
298 tempqueue.erase(iter);
299 }
300}
[6367dd]301
[690741]302const ActionQueue::ActionTokens_t ActionQueue::getListOfActions() const
303{
304 ActionTokens_t returnlist;
305
306 returnlist.insert(
307 returnlist.end(),
[ed3944]308 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getBeginIter()),
309 MapKeyConstIterator<ActionRegistry::const_iterator>(AR->getEndIter()));
[690741]310
311 return returnlist;
312}
313
[6367dd]314void ActionQueue::undoLast()
315{
316 history->undoLast();
317}
318
319void ActionQueue::redoLast()
320{
321 history->redoLast();
322}
323
324
[628577]325CONSTRUCT_SINGLETON(ActionQueue)
Note: See TracBrowser for help on using the repository browser.