source: src/Observer/Observable.cpp@ 959c82

Last change on this file since 959c82 was 959c82, checked in by Frederik Heber <heber@…>, 10 years ago

Extracted all static Observable maps (and mutex) into singleton GlobalObservableInfo.

  • this way we may safely control is destruction, i.e. it is always valid as it boils down to a primitive void pointer which does not need to be destroyed or constructed.
  • Minimized code where mutex is locked.
  • Property mode set to 100644
File size: 17.6 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * Observable.cpp
10 *
11 * Created on: Dec 1, 2011
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "CodePatterns/MemDebug.hpp"
21
22#include "CodePatterns/Observer/Observable.hpp"
23
24#include "CodePatterns/Assert.hpp"
25#include "CodePatterns/Observer/Channels.hpp"
26#include "CodePatterns/Observer/defs.hpp"
27#include "CodePatterns/Observer/Notification.hpp"
28
29#include <algorithm>
30
31#include <boost/thread/locks.hpp>
32#include <boost/thread/recursive_mutex.hpp>
33
34//!> This function does nothing with the given Observable
35void NoOp_informer(const Observable *)
36{}
37
38Observable::graveyard_informer_t Observable::noop_informer(&NoOp_informer);
39
40Observable::ChannelMap Observable::NotificationChannels;
41
42/** Attaching Sub-observables to Observables.
43 * Increases entry in Observable::(GlobalObservableInfo::getInstance().getdepth()) for this \a *publisher by one.
44 *
45 * The two functions \sa start_observer_internal() and \sa finish_observer_internal()
46 * have to be used together at all time. Never use these functions directly
47 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
48 * thus producing compiler-errors whenever only one is used.
49 * \param *publisher reference of sub-observable
50 */
51void Observable::start_observer_internal(Observable *publisher)
52{
53 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
54 // increase the count for this observable by one
55 // if no entry for this observable is found, an new one is created
56 // by the STL and initialized to 0 (see STL documentation)
57#ifdef LOG_OBSERVER
58 observerLog().addMessage((GlobalObservableInfo::getInstance().getdepth())[publisher]) << ">> Locking " << observerLog().getName(publisher);
59#endif
60 (GlobalObservableInfo::getInstance().getdepth())[publisher]++;
61}
62
63/** Detaching Sub-observables from Observables.
64 * Decreases entry in Observable::(GlobalObservableInfo::getInstance().getdepth()) for this \a *publisher by one. If zero, we
65 * start notifying all our Observers.
66 *
67 * The two functions start_observer_internal() and finish_observer_internal()
68 * have to be used together at all time. Never use these functions directly
69 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
70 * thus producing compiler-errors whenever only one is used.
71 * \param *publisher reference of sub-observable
72 */
73void Observable::finish_observer_internal(Observable *publisher)
74{
75 // decrease the count for this observable
76 // if zero is reached all observed blocks are done and we can
77 // start to notify our observers
78 int depth_publisher = 0;
79 {
80 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
81 --(GlobalObservableInfo::getInstance().getdepth())[publisher];
82#ifdef LOG_OBSERVER
83 observerLog().addMessage((GlobalObservableInfo::getInstance().getdepth())[publisher]) << "<< Unlocking " << observerLog().getName(publisher);
84#endif
85 depth_publisher = (GlobalObservableInfo::getInstance().getdepth())[publisher];
86 }
87 if(depth_publisher){}
88 else{
89 publisher->notifyAll();
90 // this item is done, so we don't have to keep the count with us
91 // save some memory by erasing it
92 {
93 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
94 (GlobalObservableInfo::getInstance().getdepth()).erase(publisher);
95 }
96 }
97}
98
99void Observable::enque_notification_internal(Observable *publisher, Notification_ptr notification)
100{
101 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
102 (GlobalObservableInfo::getInstance().getnotifications())[publisher].insert(notification);
103}
104
105/** Constructor for Observable Protector.
106 * Basically, calls start_observer_internal(). Hence use this class instead of
107 * calling the function directly.
108 *
109 * \param *protege Observable to be protected.
110 */
111Observable::_Observable_protector::_Observable_protector(Observable *_protege) :
112 protege(_protege)
113{
114 start_observer_internal(protege);
115}
116
117Observable::_Observable_protector::_Observable_protector(const _Observable_protector &dest) :
118 protege(dest.protege)
119{
120 start_observer_internal(protege);
121}
122
123/** Destructor for Observable Protector.
124 * Basically, calls finish_observer_internal(). Hence use this class instead of
125 * calling the function directly.
126 *
127 * \param *protege Observable to be protected.
128 */
129Observable::_Observable_protector::~_Observable_protector()
130{
131 finish_observer_internal(protege);
132}
133
134/************* Notification mechanism for observables **************/
135
136/** Notify all Observers of changes.
137 * Puts \a *this into Observable::(GlobalObservableInfo::getInstance().getbusyObservables()), calls Observer::update() for all in callee_t
138 * and removes from busy list.
139 */
140void Observable::notifyAll() {
141#ifdef LOG_OBSERVER
142 observerLog().addMessage() << "--> " << observerLog().getName(this)
143 << " is about to inform all its Observers.";
144#endif
145 // we are busy notifying others right now
146 // add ourselves to the list of busy subjects to enable circle detection
147 {
148 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
149 (GlobalObservableInfo::getInstance().getbusyObservables()).insert(this);
150 }
151 // see if anyone has signed up for observation
152 // and call all observers
153 try {
154 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
155 GlobalObservableInfo::calltable_t& callTable = GlobalObservableInfo::getInstance().getcallTable();
156 const bool callTable_contains = callTable.find(this) != callTable.end();
157 if (callTable_contains) {
158 // elements are stored sorted by keys in the multimap
159 // so iterating over it gives us a the callees sorted by
160 // the priorities
161 // copy such that signOff() within receiving update() does not affect iterating
162 // this is because within the same thread and with the updateKilled() signOff() may be
163 // called and when executed it modifies targets
164 GlobalObservableInfo::callees_t callees = callTable[this];
165 GlobalObservableInfo::callees_t::iterator iter;
166 for(iter=callees.begin();iter!=callees.end();++iter){
167#ifdef LOG_OBSERVER
168 observerLog().addMessage() << "-> Sending update from " << observerLog().getName(this)
169 << " to " << observerLog().getName((*iter).second)
170 << " (priority=" << (*iter).first << ")";
171#endif
172 (*iter).second->update(this);
173 }
174 }
175 }
176 ASSERT_NOCATCH("Exception thrown from Observer Update");
177
178 // send out all notifications that need to be done
179 {
180 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
181 GlobalObservableInfo::notificationSet currentNotifications =
182 (GlobalObservableInfo::getInstance().getnotifications())[this];
183 for(GlobalObservableInfo::notificationSet::iterator it = currentNotifications.begin();
184 it != currentNotifications.end();++it){
185 (*it)->notifyAll(this);
186 }
187 }
188
189 {
190 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
191 (GlobalObservableInfo::getInstance().getnotifications()).erase(this);
192
193 // done with notification, we can leave the set of busy subjects
194 (GlobalObservableInfo::getInstance().getbusyObservables()).erase(this);
195 }
196
197#ifdef LOG_OBSERVER
198 observerLog().addMessage() << "--> " << observerLog().getName(this)
199 << " is done informing all its Observers.";
200#endif
201}
202
203
204/** Handles passing on updates from sub-Observables.
205 * Mimicks basically the Observer::update() function.
206 *
207 * \param *publisher The \a *this we observe.
208 */
209void Observable::update(Observable *publisher) {
210 // circle detection
211 bool presentCircle = false;
212 {
213 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
214 presentCircle = (GlobalObservableInfo::getInstance().getbusyObservables()).find(this)!=(GlobalObservableInfo::getInstance().getbusyObservables()).end();
215 }
216 if(presentCircle) {
217 // somehow a circle was introduced... we were busy notifying our
218 // observers, but still we are called by one of our sub-Observables
219 // we cannot be sure observation will still work at this point
220 ASSERT(0,"Circle detected in observation-graph.\n"
221 "Observation-graph always needs to be a DAG to work correctly!\n"
222 "Please check your observation code and fix this!\n");
223 return;
224 }
225 else {
226 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
227 // see if we are in the process of changing ourselves
228 // if we are changing ourselves at the same time our sub-observables change
229 // we do not need to publish all the changes at each time we are called
230 std::map<Observable*, int>& depth = GlobalObservableInfo::getInstance().getdepth();
231 const bool depth_contains = depth.find(this)==depth.end();
232 if(depth_contains) {
233#ifdef LOG_OBSERVER
234 observerLog().addMessage() << "-* Update from " << observerLog().getName(publisher)
235 << " propagated by " << observerLog().getName(this);
236#endif
237 notifyAll();
238 }
239 else{
240#ifdef LOG_OBSERVER
241 observerLog().addMessage() << "-| Update from " << observerLog().getName(publisher)
242 << " not propagated by " << observerLog().getName(this);
243#endif
244 }
245 }
246}
247
248/** Sign on an Observer to this Observable.
249 * Puts \a *target into Observable::(GlobalObservableInfo::getInstance().getcallTable()) list.
250 * \param *target Observer
251 * \param priority number in [-20,20]
252 */
253void Observable::signOn(Observer *target, GlobalObservableInfo::PriorityLevel priority) const
254{
255#ifdef LOG_OBSERVER
256 observerLog().addMessage() << "@@ Signing on " << observerLog().getName(target) << " to " << observerLog().getName(const_cast<Observable *>(this));
257#endif
258 bool res = false;
259 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
260 GlobalObservableInfo::callees_t &callees = (GlobalObservableInfo::getInstance().getcallTable())[const_cast<Observable *>(this)];
261
262 GlobalObservableInfo::callees_t::iterator iter;
263 for(iter=callees.begin();iter!=callees.end();++iter){
264 res |= ((*iter).second == target);
265 }
266 if(!res)
267 callees.insert(std::pair<int,Observer*>(priority.level,target));
268}
269
270/** Sign off an Observer from this Observable.
271 * Removes \a *target from Observable::(GlobalObservableInfo::getInstance().getcallTable()) list.
272 * \param *target Observer
273 */
274void Observable::signOff(Observer *target) const
275{
276 {
277 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
278 GlobalObservableInfo::calltable_t &callTable = GlobalObservableInfo::getInstance().getcallTable();
279 ASSERT(callTable.count(const_cast<Observable *>(this)),
280 "SignOff called for an Observable without Observers.");
281#ifdef LOG_OBSERVER
282 observerLog().addMessage() << "** Signing off " << observerLog().getName(target) << " from " << observerLog().getName(const_cast<Observable *>(this));
283#endif
284 GlobalObservableInfo::callees_t &callees = callTable[const_cast<Observable *>(this)];
285
286 GlobalObservableInfo::callees_t::iterator iter;
287 GlobalObservableInfo::callees_t::iterator deliter;
288 for(iter=callees.begin();iter!=callees.end();) {
289 if((*iter).second == target) {
290 callees.erase(iter++);
291 }
292 else {
293 ++iter;
294 }
295 }
296 if(callees.empty()){
297 callTable.erase(const_cast<Observable *>(this));
298 }
299 }
300 (*graveyard_informer)(this);
301}
302
303void Observable::signOn(
304 Observer *target,
305 size_t channelno,
306 GlobalObservableInfo::PriorityLevel priority) const
307{
308 Notification_ptr notification = getChannel(channelno);
309#ifdef LOG_OBSERVER
310 observerLog().addMessage() << "@@ Signing on " << observerLog().getName(target)
311 << " to " << observerLog().getName(const_cast<Observable *>(this))
312 << "'s channel no." << channelno << ".";
313#endif
314 notification->addObserver(target, priority.level);
315}
316
317void Observable::signOff(Observer *target, size_t channelno) const
318{
319 Notification_ptr notification = getChannel(channelno);
320#ifdef LOG_OBSERVER
321 observerLog().addMessage() << "** Signing off " << observerLog().getName(target)
322 << " from " << observerLog().getName(const_cast<Observable *>(this))
323 << "'s channel no." << channelno << ".";
324#endif
325 notification->removeObserver(target);
326 (*graveyard_informer)(this);
327}
328
329bool Observable::isBlocked() const
330{
331 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
332 return (GlobalObservableInfo::getInstance().getdepth()).count(const_cast<Observable *>(this)) > 0;
333}
334
335Notification_ptr Observable::getChannel(size_t no) const
336{
337 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
338 const ChannelMap::const_iterator iter = NotificationChannels.find(const_cast<Observable *>(this));
339 const bool status = iter != NotificationChannels.end();
340 Channels *OurChannel = NULL;
341 if (status)
342 OurChannel = iter->second;
343 ASSERT(status,
344 "Observable::getChannel() - we do not have a channel "+toString(no)+" in NotificationChannels.");
345 ASSERT(OurChannel != NULL,
346 "Observable::getChannel() - observable has no channels.");
347 return OurChannel->getChannel(no);
348}
349
350size_t Observable::getNumberOfObservers() const
351{
352 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
353 size_t ObserverCount = 0;
354 {
355 GlobalObservableInfo::calltable_t &callTable = GlobalObservableInfo::getInstance().getcallTable();
356 GlobalObservableInfo::calltable_t::const_iterator callees_t_iter =
357 callTable.find(const_cast<Observable *>(this));
358 // if not present, then we have zero observers
359 if (callees_t_iter != callTable.end())
360 ObserverCount += callees_t_iter->second.size();
361 }
362 {
363 const ChannelMap::const_iterator iter =
364 NotificationChannels.find(const_cast<Observable *>(this));
365 // if not present, then we have zero observers
366 if (iter != NotificationChannels.end())
367 for (Channels::NotificationTypetoRefMap::const_iterator channeliter = iter->second->ChannelMap.begin();
368 channeliter != iter->second->ChannelMap.end();
369 ++channeliter)
370 ObserverCount += (channeliter->second)->getNumberOfObservers();
371 }
372 return ObserverCount;
373}
374
375/** Handles sub-observables that just got killed
376 * when an sub-observerable dies we usually don't need to do anything
377 * \param *publisher Sub-Observable.
378 */
379void Observable::subjectKilled(Observable *publisher)
380{
381}
382
383/** Constructor for class Observable.
384 */
385Observable::Observable(
386 std::string name,
387 const channels_t &_channels) :
388 Observer(Observer::BaseConstructor()),
389 graveyard_informer(&noop_informer)
390{
391#ifdef LOG_OBSERVER
392 observerLog().addName(this,name);
393 observerLog().addMessage() << "++ Creating Observable "
394 << observerLog().getName(static_cast<Observable *>(this));
395#endif
396
397 if (!_channels.empty()) {
398 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
399 Channels *OurChannel = new Channels;
400 NotificationChannels.insert( std::make_pair(static_cast<Observable *>(this), OurChannel) );
401 // add instance for each notification type
402 for (channels_t::const_iterator iter = _channels.begin();
403 iter != _channels.end(); ++iter)
404 OurChannel->addChannel(*iter);
405 }
406}
407
408/** Destructor for class Observable.
409 * When an observable is deleted, we let all our observers know. \sa Observable::subjectKilled().
410 */
411Observable::~Observable()
412{
413#ifdef LOG_OBSERVER
414 observerLog().addMessage() << "-- Destroying Observable "
415 << observerLog().getName(static_cast<Observable *>(this));
416#endif
417 bool CallTable_contains = false;
418 {
419 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
420 CallTable_contains = (GlobalObservableInfo::getInstance().getcallTable()).count(this);
421 }
422 if(CallTable_contains) {
423 // copy the list from the map
424 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
425 // copy such that signOff() within receiving subjectKilled() does not affect iterating
426 // this is because within the same thread and with the subjectKilled() signOff() may be
427 // called and when executed it modifies targets
428 GlobalObservableInfo::callees_t callees = (GlobalObservableInfo::getInstance().getcallTable())[this];
429 // delete all entries for this observable
430 GlobalObservableInfo::callees_t::iterator iter;
431 for(iter=callees.begin();iter!=callees.end();++iter)
432 (*iter).second->subjectKilled(this);
433 // erase the list in the map
434 (GlobalObservableInfo::getInstance().getcallTable()).erase(this);
435 }
436
437 // also kill instance in static Channels map if present
438 {
439 boost::recursive_mutex::scoped_lock lock(GlobalObservableInfo::getInstance().getObservablesMapMutex());
440 ChannelMap::iterator iter = NotificationChannels.find(static_cast<Observable *>(this));
441 if (iter != NotificationChannels.end()) {
442 iter->second->subjectKilled(static_cast<Observable *>(this));
443 delete iter->second;
444 NotificationChannels.erase(iter);
445 }
446 }
447}
448
449Observable::channels_t Observable::getChannelList(const size_t max)
450{
451 channels_t channels(max);
452 std::generate(channels.begin(), channels.end(), UniqueNumber());
453 return channels;
454}
Note: See TracBrowser for help on using the repository browser.