source: src/Patterns/Observer.cpp@ c296c2

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 c296c2 was c296c2, checked in by Frederik Heber <heber@…>, 15 years ago

MEMLEAK: Observable::signOff() erases its own iterator, some more documentation added

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