/
observable.hpp
576 lines (468 loc) · 18.7 KB
/
observable.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
Copyright (C) 2003, 2004, 2005, 2006 StatPro Italia srl
Copyright (C) 2011, 2012 Ferdinando Ametrano
Copyright (C) 2013 Chris Higgs
Copyright (C) 2015 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file observable.hpp
\brief observer/observable pattern
*/
#ifndef quantlib_observable_hpp
#define quantlib_observable_hpp
#include <ql/errors.hpp>
#include <ql/types.hpp>
#include <ql/patterns/singleton.hpp>
#include <ql/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
#ifndef QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN
// Boost libraries prior to 1.47 have a bug in the hash function,
// which makes boost::unordered_set very inefficient if the key is of type
// ext::shared_ptr. In this case fall back to std::set.
#if BOOST_VERSION < 104700
#include <set>
#endif
namespace QuantLib {
class Observer;
class Observable;
//! global repository for run-time library settings
class ObservableSettings : public Singleton<ObservableSettings> {
friend class Singleton<ObservableSettings>;
friend class Observable;
public:
void disableUpdates(bool deferred=false) {
updatesEnabled_ = false;
updatesDeferred_ = deferred;
}
void enableUpdates();
bool updatesEnabled() {return updatesEnabled_;}
bool updatesDeferred() {return updatesDeferred_;}
private:
ObservableSettings()
: updatesEnabled_(true),
updatesDeferred_(false) {}
void registerDeferredObservers(
const boost::unordered_set<Observer*>& observers);
void unregisterDeferredObserver(Observer*);
typedef boost::unordered_set<Observer*> set_type;
typedef set_type::iterator iterator;
set_type deferredObservers_;
bool updatesEnabled_, updatesDeferred_;
};
//! Object that notifies its changes to a set of observers
/*! \ingroup patterns */
class Observable {
friend class Observer;
public:
// constructors, assignment, destructor
Observable() : settings_(ObservableSettings::instance()) {}
Observable(const Observable&);
Observable& operator=(const Observable&);
virtual ~Observable() {}
/*! This method should be called at the end of non-const methods
or when the programmer desires to notify any changes.
*/
void notifyObservers();
private:
typedef boost::unordered_set<Observer*>::iterator iterator;
std::pair<iterator, bool> registerObserver(Observer*);
Size unregisterObserver(Observer*);
boost::unordered_set<Observer*> observers_;
ObservableSettings& settings_;
};
//! Object that gets notified when a given observable changes
/*! \ingroup patterns */
class Observer {
public:
#if BOOST_VERSION < 104700
typedef std::set<ext::shared_ptr<Observable> > set_type;
#else
typedef boost::unordered_set<ext::shared_ptr<Observable> > set_type;
#endif
typedef set_type::iterator iterator;
// constructors, assignment, destructor
Observer() {}
Observer(const Observer&);
Observer& operator=(const Observer&);
virtual ~Observer();
// observer interface
std::pair<iterator, bool>
registerWith(const ext::shared_ptr<Observable>&);
/*! register with all observables of a given observer. Note
that this does not include registering with the observer
itself. */
void registerWithObservables(const ext::shared_ptr<Observer>&);
Size unregisterWith(const ext::shared_ptr<Observable>&);
void unregisterWithAll();
/*! This method must be implemented in derived classes. An
instance of %Observer does not call this method directly:
instead, it will be called by the observables the instance
registered with when they need to notify any changes.
*/
virtual void update() = 0;
/*! This method allows to explicitly update the instance itself
and nested observers. If notifications are disabled a call to
this method ensures an update of such nested observers. It
should be implemented in derived classes whenever applicable */
virtual void deepUpdate();
private:
set_type observables_;
};
// inline definitions
inline void ObservableSettings::registerDeferredObservers(
const boost::unordered_set<Observer*>& observers) {
if (updatesDeferred()) {
deferredObservers_.insert(observers.begin(), observers.end());
}
}
inline void ObservableSettings::unregisterDeferredObserver(Observer* o) {
deferredObservers_.erase(o);
}
inline Observable::Observable(const Observable&)
: settings_(ObservableSettings::instance()) {
// the observer set is not copied; no observer asked to
// register with this object
}
/*! \warning notification is sent before the copy constructor has
a chance of actually change the data
members. Therefore, observers whose update() method
tries to use their observables will not see the
updated values. It is suggested that the update()
method just raise a flag in order to trigger
a later recalculation.
*/
inline Observable& Observable::operator=(const Observable& o) {
// as above, the observer set is not copied. Moreover,
// observers of this object must be notified of the change
if (&o != this)
notifyObservers();
return *this;
}
inline std::pair<boost::unordered_set<Observer*>::iterator, bool>
Observable::registerObserver(Observer* o) {
return observers_.insert(o);
}
inline Size Observable::unregisterObserver(Observer* o) {
if (settings_.updatesDeferred())
settings_.unregisterDeferredObserver(o);
return observers_.erase(o);
}
inline Observer::Observer(const Observer& o)
: observables_(o.observables_) {
for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->registerObserver(this);
}
inline Observer& Observer::operator=(const Observer& o) {
iterator i;
for (i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->unregisterObserver(this);
observables_ = o.observables_;
for (i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->registerObserver(this);
return *this;
}
inline Observer::~Observer() {
for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->unregisterObserver(this);
}
inline std::pair<Observer::iterator, bool>
Observer::registerWith(const ext::shared_ptr<Observable>& h) {
if (h) {
h->registerObserver(this);
return observables_.insert(h);
}
return std::make_pair(observables_.end(), false);
}
inline void
Observer::registerWithObservables(const ext::shared_ptr<Observer> &o) {
if (o) {
iterator i;
for (i = o->observables_.begin(); i != o->observables_.end(); ++i)
registerWith(*i);
}
}
inline
Size Observer::unregisterWith(const ext::shared_ptr<Observable>& h) {
if (h)
h->unregisterObserver(this);
return observables_.erase(h);
}
inline void Observer::unregisterWithAll() {
for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->unregisterObserver(this);
observables_.clear();
}
inline void Observer::deepUpdate() {
update();
}
}
#else
#include <boost/atomic.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/smart_ptr/owner_less.hpp>
#include <set>
namespace QuantLib {
class Observable;
class ObservableSettings;
//! Object that gets notified when a given observable changes
/*! \ingroup patterns */
class Observer : public ext::enable_shared_from_this<Observer> {
friend class Observable;
friend class ObservableSettings;
public:
typedef boost::unordered_set<ext::shared_ptr<Observable> > set_type;
typedef set_type::iterator iterator;
// constructors, assignment, destructor
Observer() {}
Observer(const Observer&);
Observer& operator=(const Observer&);
virtual ~Observer();
// observer interface
std::pair<iterator, bool>
registerWith(const ext::shared_ptr<Observable>&);
/*! register with all observables of a given observer. Note
that this does not include registering with the observer
itself. */
void registerWithObservables(const ext::shared_ptr<Observer>&);
Size unregisterWith(const ext::shared_ptr<Observable>&);
void unregisterWithAll();
/*! This method must be implemented in derived classes. An
instance of %Observer does not call this method directly:
instead, it will be called by the observables the instance
registered with when they need to notify any changes.
*/
virtual void update() = 0;
/*! This method allows to explicitly update the instance itself
and nested observers. If notifications are disabled a call to
this method ensures an update of such nested observers. It
should be implemented in derived classes whenever applicable */
virtual void deepUpdate();
private:
class Proxy {
public:
explicit Proxy(Observer* const observer)
: active_ (true),
observer_(observer) {
}
void update() const {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
if (active_) {
// c++17 is required if used with std::shared_ptr<T>
const ext::weak_ptr<Observer> o
= observer_->weak_from_this();
//check for empty weak reference
//https://stackoverflow.com/questions/45507041/how-to-check-if-weak-ptr-is-empty-non-assigned
const ext::weak_ptr<Observer> empty;
if (o.owner_before(empty) || empty.owner_before(o)) {
const ext::shared_ptr<Observer> obs(o.lock());
if (obs)
obs->update();
}
else {
observer_->update();
}
}
}
void deactivate() {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
active_ = false;
}
private:
bool active_;
mutable boost::recursive_mutex mutex_;
Observer* const observer_;
};
ext::shared_ptr<Proxy> proxy_;
mutable boost::recursive_mutex mutex_;
set_type observables_;
};
namespace detail {
class Signal;
}
//! Object that notifies its changes to a set of observers
/*! \ingroup patterns */
class Observable {
friend class Observer;
public:
typedef boost::unordered_set<ext::shared_ptr<Observer::Proxy> >
set_type;
typedef set_type::iterator iterator;
// constructors, assignment, destructor
Observable();
Observable(const Observable&);
Observable& operator=(const Observable&);
virtual ~Observable() {}
/*! This method should be called at the end of non-const methods
or when the programmer desires to notify any changes.
*/
void notifyObservers();
private:
void registerObserver(const ext::shared_ptr<Observer::Proxy>&);
void unregisterObserver(const ext::shared_ptr<Observer::Proxy>&);
ext::shared_ptr<detail::Signal> sig_;
set_type observers_;
mutable boost::recursive_mutex mutex_;
ObservableSettings& settings_;
};
//! global repository for run-time library settings
class ObservableSettings : public Singleton<ObservableSettings> {
friend class Singleton<ObservableSettings>;
friend class Observable;
public:
void disableUpdates(bool deferred=false) {
boost::lock_guard<boost::mutex> lock(mutex_);
updatesType_ = (deferred) ? UpdatesDeferred : 0;
}
void enableUpdates();
bool updatesEnabled() {return (updatesType_ & UpdatesEnabled) != 0; }
bool updatesDeferred() {return (updatesType_ & UpdatesDeferred) != 0; }
private:
ObservableSettings() : updatesType_(UpdatesEnabled) {}
typedef std::set<ext::weak_ptr<Observer::Proxy>,
boost::owner_less<ext::weak_ptr<Observer::Proxy> > >
set_type;
typedef set_type::iterator iterator;
void registerDeferredObservers(const Observable::set_type& observers);
void unregisterDeferredObserver(
const ext::shared_ptr<Observer::Proxy>& proxy);
set_type deferredObservers_;
mutable boost::mutex mutex_;
enum UpdateType { UpdatesEnabled = 1, UpdatesDeferred = 2} ;
boost::atomic<int> updatesType_;
};
// inline definitions
inline void ObservableSettings::registerDeferredObservers(
const Observable::set_type& observers) {
deferredObservers_.insert(observers.begin(), observers.end());
}
inline void ObservableSettings::unregisterDeferredObserver(
const ext::shared_ptr<Observer::Proxy>& o) {
deferredObservers_.erase(o);
}
inline void ObservableSettings::enableUpdates() {
boost::lock_guard<boost::mutex> lock(mutex_);
// if there are outstanding deferred updates, do the notification
updatesType_ = UpdatesEnabled;
if (deferredObservers_.size()) {
bool successful = true;
std::string errMsg;
for (iterator i=deferredObservers_.begin();
i!=deferredObservers_.end(); ++i) {
try {
const ext::shared_ptr<Observer::Proxy> proxy = i->lock();
if (proxy)
proxy->update();
} catch (std::exception& e) {
successful = false;
errMsg = e.what();
} catch (...) {
successful = false;
}
}
deferredObservers_.clear();
QL_ENSURE(successful,
"could not notify one or more observers: " << errMsg);
}
}
/*! \warning notification is sent before the copy constructor has
a chance of actually change the data
members. Therefore, observers whose update() method
tries to use their observables will not see the
updated values. It is suggested that the update()
method just raise a flag in order to trigger
a later recalculation.
*/
inline Observable& Observable::operator=(const Observable& o) {
// as above, the observer set is not copied. Moreover,
// observers of this object must be notified of the change
if (&o != this)
notifyObservers();
return *this;
}
inline Observer::Observer(const Observer& o) {
proxy_.reset(new Proxy(this));
{
boost::lock_guard<boost::recursive_mutex> lock(o.mutex_);
observables_ = o.observables_;
}
for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->registerObserver(proxy_);
}
inline Observer& Observer::operator=(const Observer& o) {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
if (!proxy_) {
proxy_.reset(new Proxy(this));
}
iterator i;
for (i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->unregisterObserver(proxy_);
{
boost::lock_guard<boost::recursive_mutex> lock(o.mutex_);
observables_ = o.observables_;
}
for (i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->registerObserver(proxy_);
return *this;
}
inline Observer::~Observer() {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
if (proxy_)
proxy_->deactivate();
for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->unregisterObserver(proxy_);
}
inline std::pair<Observer::iterator, bool>
Observer::registerWith(const ext::shared_ptr<Observable>& h) {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
if (!proxy_) {
proxy_.reset(new Proxy(this));
}
if (h) {
h->registerObserver(proxy_);
return observables_.insert(h);
}
return std::make_pair(observables_.end(), false);
}
inline void
Observer::registerWithObservables(const ext::shared_ptr<Observer>& o) {
if (o) {
boost::lock_guard<boost::recursive_mutex> lock(o->mutex_);
for (iterator i = o->observables_.begin();
i != o->observables_.end(); ++i)
registerWith(*i);
}
}
inline
Size Observer::unregisterWith(const ext::shared_ptr<Observable>& h) {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
if (h) {
QL_REQUIRE(proxy_, "unregister called without a proxy");
h->unregisterObserver(proxy_);
}
return observables_.erase(h);
}
inline void Observer::unregisterWithAll() {
boost::lock_guard<boost::recursive_mutex> lock(mutex_);
for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
(*i)->unregisterObserver(proxy_);
observables_.clear();
}
inline void Observer::deepUpdate() {
update();
}
}
#endif
#endif