source: src/Actions/ActionQueue.cpp@ caece4

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 caece4 was 74459a, checked in by Frederik Heber <heber@…>, 11 years ago

Added --disable-action-thread to allow disabling of extra run thread.

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