source: src/Patterns/Observer.cpp@ 05a97c

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 05a97c was b64313, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Improved Observer Framework to include methods to report the state

  • bool Observable::isBlocked() will tell if the Observer is currently updating itself
  • The Circle detection test now uses ASSERT to report when a circle was detected (can be caught by CPPUNIT)
  • Property mode set to 100644
File size: 7.7 KB
Line 
1/*
2 * Observer.cpp
3 *
4 * Created on: Jan 19, 2010
5 * Author: crueger
6 */
7
8#include "Observer.hpp"
9
10
11#include <iostream>
12
13#include "Helpers/Assert.hpp"
14
15using namespace std;
16
17/****************** Static stuff for the observer mechanism ************/
18
19// All infrastructure for the observer-pattern is bundled at a central place
20// this is more efficient if many objects can be observed (inherit from observable)
21// but only few are actually coupled with observers. E.g. TMV has over 500.000 Atoms,
22// which might become observable. Handling Observerable infrastructure in each of
23// these would use memory for each atom. By handling Observer-infrastructure
24// here we only need memory for objects that actually are observed.
25// See [Gamma et al, 1995] p. 297
26
27map<Observable*, int> Observable::depth; //!< Map of Observables to the depth of the DAG of Observers
28map<Observable*,multimap<int,Observer*>*> Observable::callTable; //!< Table for each Observable of all its Observers
29set<Observable*> Observable::busyObservables; //!< Set of Observables that are currently busy notifying their sign-on'ed Observers
30
31/** Attaching Sub-observables to Observables.
32 * Increases entry in Observable::depth for this \a *publisher by one.
33 *
34 * The two functions \sa start_observer_internal() and \sa finish_observer_internal()
35 * have to be used together at all time. Never use these functions directly
36 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
37 * thus producing compiler-errors whenever only one is used.
38 * \param *publisher reference of sub-observable
39 */
40void Observable::start_observer_internal(Observable *publisher){
41 // increase the count for this observable by one
42 // if no entry for this observable is found, an new one is created
43 // by the STL and initialized to 0 (see STL documentation)
44 depth[publisher]++;
45}
46
47/** Detaching Sub-observables from Observables.
48 * Decreases entry in Observable::depth for this \a *publisher by one. If zero, we
49 * start notifying all our Observers.
50 *
51 * The two functions start_observer_internal() and finish_observer_internal()
52 * have to be used together at all time. Never use these functions directly
53 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
54 * thus producing compiler-errors whenever only one is used.
55 * \param *publisher reference of sub-observable
56 */
57void Observable::finish_observer_internal(Observable *publisher){
58 // decrease the count for this observable
59 // if zero is reached all observed blocks are done and we can
60 // start to notify our observers
61 if(--(depth[publisher])){}
62 else{
63 publisher->notifyAll();
64 // this item is done, so we don't have to keep the count with us
65 // save some memory by erasing it
66 depth.erase(publisher);
67 }
68}
69
70/** Constructor for Observable Protector.
71 * Basically, calls start_observer_internal(). Hence use this class instead of
72 * calling the function directly.
73 *
74 * \param *protege Observable to be protected.
75 */
76Observable::_Observable_protector::_Observable_protector(Observable *_protege) :
77 protege(_protege)
78{
79 start_observer_internal(protege);
80}
81
82Observable::_Observable_protector::_Observable_protector(const _Observable_protector &dest) :
83 protege(dest.protege)
84{
85 start_observer_internal(protege);
86}
87
88/** Destructor for Observable Protector.
89 * Basically, calls finish_observer_internal(). Hence use this class instead of
90 * calling the function directly.
91 *
92 * \param *protege Observable to be protected.
93 */
94Observable::_Observable_protector::~_Observable_protector()
95{
96 finish_observer_internal(protege);
97}
98
99/************* Notification mechanism for observables **************/
100
101/** Notify all Observers of changes.
102 * Puts \a *this into Observable::busyObservables, calls Observer::update() for all in callee_t
103 * and removes from busy list.
104 */
105void Observable::notifyAll() {
106 // we are busy notifying others right now
107 // add ourselves to the list of busy subjects to enable circle detection
108 busyObservables.insert(this);
109 // see if anyone has signed up for observation
110 // and call all observers
111 if(callTable.count(this)) {
112 // elements are stored sorted by keys in the multimap
113 // so iterating over it gives us a the callees sorted by
114 // the priorities
115 callees_t *callees = callTable[this];
116 callees_t::iterator iter;
117 for(iter=callees->begin();iter!=callees->end();++iter){
118 (*iter).second->update(this);
119 }
120 }
121 // done with notification, we can leave the set of busy subjects
122 busyObservables.erase(this);
123}
124
125/** Handles passing on updates from sub-Observables.
126 * Mimicks basically the Observer::update() function.
127 *
128 * \param *publisher The \a *this we observe.
129 */
130void Observable::update(Observable *publisher) {
131 // circle detection
132 if(busyObservables.find(this)!=busyObservables.end()) {
133 // somehow a circle was introduced... we were busy notifying our
134 // observers, but still we are called by one of our sub-Observables
135 // we cannot be sure observation will still work at this point
136 ASSERT(0,"Circle detected in observation-graph.\n"
137 "Observation-graph always needs to be a DAG to work correctly!\n"
138 "Please check your observation code and fix this!\n");
139 return;
140 }
141 else {
142 // see if we are in the process of changing ourselves
143 // if we are changing ourselves at the same time our sub-observables change
144 // we do not need to publish all the changes at each time we are called
145 if(depth.find(this)==depth.end()) {
146 notifyAll();
147 }
148 }
149}
150
151/** Sign on an Observer to this Observable.
152 * Puts \a *target into Observable::callTable list.
153 * \param *target Observer
154 * \param priority number in [-20,20]
155 */
156void Observable::signOn(Observer *target,int priority) {
157 ASSERT(priority>=-20 && priority<=+20, "Priority out of range [-20:+20] when signing on Observer");
158 bool res = false;
159 callees_t *callees = 0;
160 if(callTable.count(this)){
161 callees = callTable[this];
162 }
163 else {
164 callees = new multimap<int,Observer*>;
165 callTable.insert(pair<Observable*,callees_t*>(this,callees));
166 }
167
168 callees_t::iterator iter;
169 for(iter=callees->begin();iter!=callees->end();++iter){
170 res |= ((*iter).second == target);
171 }
172 if(!res)
173 callees->insert(pair<int,Observer*>(priority,target));
174}
175
176/** Sign off an Observer from this Observable.
177 * Removes \a *target from Observable::callTable list.
178 * \param *target Observer
179 */
180void Observable::signOff(Observer *target) {
181 ASSERT(callTable.count(this),"SignOff called for an Observable without Observers.");
182 callees_t *callees = callTable[this];
183 callees_t::iterator iter;
184 callees_t::iterator deliter;
185 for(iter=callees->begin();iter!=callees->end();) {
186 if((*iter).second == target) {
187 callees->erase(iter++);
188 }
189 else {
190 ++iter;
191 }
192 }
193 if(callees->empty()){
194 callTable.erase(this);
195 delete callees;
196 }
197}
198
199bool Observable::isBlocked(){
200 return depth.count(this) > 0;
201}
202
203/** Handles sub-observables that just got killed
204 * when an sub-observerable dies we usually don't need to do anything
205 * \param *publisher Sub-Observable.
206 */
207void Observable::subjectKilled(Observable *publisher){
208}
209
210/** Constructor for class Observable.
211 */
212Observable::Observable()
213{}
214
215/** Destructor for class Observable.
216 * When an observable is deleted, we let all our observers know. \sa Observable::subjectKilled().
217 */
218Observable::~Observable()
219{
220 if(callTable.count(this)) {
221 // delete all entries for this observable
222 callees_t *callees = callTable[this];
223 callees_t::iterator iter;
224 for(iter=callees->begin();iter!=callees->end();++iter){
225 (*iter).second->subjectKilled(this);
226 }
227 callTable.erase(this);
228 delete callees;
229 }
230}
231
232/** Constructor for class Observer.
233 */
234Observer::Observer()
235{}
236
237/** Destructor for class Observer.
238 */
239Observer::~Observer()
240{}
Note: See TracBrowser for help on using the repository browser.