【发布时间】:2015-08-25 04:18:54
【问题描述】:
我在 Activity 线程中有一个通知中心:
Poco::NotificationCentre nc; // publicly visible
// (thread main loop which will post notifications from time to time)
还有多个作用于通知的工作线程。然而,那些等待通知的线程也可能需要在外部发出信号以随时退出。所以我在我的工作线程中有以下内容(这也是伪代码,为了清楚起见省略了一些细节)
Poco::Event event;
std::string s;
MyNotificationClass notifier{event, s}; // holds those by reference
Poco::NObserver<MyNotificationClass, MyNotification> obs(notifier, &MyNoficationClass::func);
nc.addObserver(obs);
event.wait();
nc.removeObserver(obs);
return s;
通知类是:
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;
};
我担心的是,即使在工作线程中调用removeObserver之后,通知中心也可能同时收到了通知,所以工作线程具有的函数中的对象s刚刚returned from 在它被销毁后可能会被访问。
我的问题是:这是一个有效的问题吗?如果是,我应该怎么做才能确保在return 之后不会发生通知?
【问题讨论】:
标签: c++ multithreading poco-libraries