c++ - Poco - using removeObserver safely -
i have notification centre in activity thread:
poco::notificationcentre nc; // publicly visible // (thread main loop post notifications time time)
and multiple worker threads act on notification. threads waiting notification may need signalled externally exit @ time. have got following in worker threads (again pseudocode omitting details clarity)
poco::event event; std::string s; mynotificationclass notifier{event, s}; // holds reference poco::nobserver<mynotificationclass, mynotification> obs(notifier, &mynoficationclass::func); nc.addobserver(obs); event.wait(); nc.removeobserver(obs); return s;
the notification class is:
struct mynotificationclass { mynotificationclass(poco::event &ev, std::string &s): ev(ev), s(s) {} void func(const poco::autoptr<mynotification> &p) { s = p->s; ev.set(); } poco::event &ev; std::string &s; };
what worried after removeobserver
called in worker thread, notification centre might have been simultaneously having notification posted it, object s
in function worker thread has return
ed might accessed after has been destroyed.
my question is: valid concern, , if so, should make sure no notification occur after return
?
edit: since removeobserver()
disabling removed observer, above code safe. answer below left record make sense of comments section.
original answer:
it valid concern - worker thread function can preempted between add/removeobserver() calls. since postnotification()
makes copy* of observers' pointers, if there multiple notifications other threads, pointer observer may still in 1 or more copy list(s) after call removeobserver()
(or after function returns).
now, there no need worry observer being accessed after function returns because cloned sharedptr notificationcenter. there is, however, concern notification handler being called @ time because nobserver holds naked address. prevent bad things happen, call obs.disable()
before returning function - disarm notification handling pending notifications in thread-safe fashion.
* for performance reasons - not want block rest of notificationcenter while notification handlers executing.
Comments
Post a Comment