【发布时间】:2012-01-11 23:53:42
【问题描述】:
这是我实现 C++ 事件的尝试。
class Event{
typedef std::tr1::function<void( int& )> CallbackFunction;
std::list< CallbackFunction > m_handlers;
template<class M>
void AddHandler(M& thisPtr, void typename (M::*callback)(int&))
{
CallbackFunction bound = std::tr1::bind(callback, &thisPtr, _1);
m_handlers.push_back(bound);
}
void operator()(int& eventArg)
{
iterate over list...
(*iter)(eventArg);
}}
这里的问题是线程安全。如果同时调用 AddHandler 和 operator(),事情可能会中断。
同步这个的最佳方式是什么?使用互斥锁可能会降低性能。我想知道在这种情况下 boost::signals 或 C# 事件的幕后会发生什么。
【问题讨论】:
-
他们每秒被调用的频率是多少?为什么同一个对象需要对所有线程都可用?他们不能都只发送一个线程接收的互斥消息吗?
标签: c++ multithreading events delegates