事件系统优化
event system optimization
如果我有这些声明和定义:
enum Events
{
INIT,
RENDER
};
struct EventBase
{
typedef void (EventBase::*event_callback_type)();
~EventBase() {}
virtual void init() { assert(0); }
virtual void render() { assert(0); }
};
template <enum Events>
struct EventTraits
{
static EventBase::event_callback_type const event_callback;
};
// in a .cpp file
template <>
EventBase::event_callback_type const
EventTraits<INIT>::event_callback(
&EventBase::init);
template <>
EventBase::event_callback_type const
EventTraits<RENDER>::event_callback(
&EventBase::render);
// in another class *i are pointers to objects that inherit EventBase
template <enum Events event>
inline void EventNotifier::notify()
{
for (events_type::const_iterator i(event_handlers[event].begin());
i != event_handlers[event].begin() + num_event_handlers[event];
++i)
{
((*i)->*EventTraits<event>::event_callback)();
if ((*i)->num_event_handlers[event])
{
(*i)->notify<event>();
}
// else do nothing
}
}
假设事件 RENDER 需要尽可能快的处理,您认为是否值得进行成员模板专用化:
template <>
inline void EventNotifier::notify<RENDER>()
{
for (events_type::const_iterator i(event_handlers[RENDER].begin());
i != event_handlers[RENDER].begin() + num_event_handlers[RENDER];
++i)
{
(*i)->render();
if ((*i)->num_event_handlers[RENDER])
{
(*i)->notify<RENDER>();
}
// else do nothing
}
}
这不需要获取指向成员函数的静态指针。或者也许我应该这样做:
template <enum Events>
struct EventTraits
{
static EventBase::event_callback_type event_callback();
};
并专门化结构模板?
只需额外支付 5 美分。EventNotifier::notify(( 看起来完全线程不安全。此外,如果任何事件处理程序生成新的事件,则可能发生不好的事情。我建议以这种方式进行通知(C++ 11,只是不知道您的所有类型(:
template <> inline void EventNotifier::notify<RENDER>()
{
decltype(event_handlers[RENDER]) local;
decltype(num_event_handlers[RENDER]) local_num;
{
std::lock_guard<std::mutex> guard(my_mutex);
local = event_handlers[RENDER];
local_num = num_event_handlers[RENDER];
}
for (events_type::const_iterator i(local.begin()); i != local.begin() + local_num; ++i)
{
(*i)->render();
if ((*i)->num_event_handlers[RENDER]) (*i)->notify<RENDER>();
}
}
成员专业化不会对其当前形式产生任何影响,因为您编写的代码与编译器将为您生成的代码相同。
这里有一个小的改进:
template <enum Events event>
inline void EventNotifier::notify()
{
for (events_type::const_iterator i(event_handlers[event].begin()),
end (event_handlers[event].begin() + num_event_handlers[event]);
i != end; ++i)
{
((*i)->*EventTraits<event>::event_callback)();
if ((*i)->num_event_handlers[event])
{
(*i)->notify<event>();
}
// else do nothing
}
}
相关文章:
- C++事件系统 - 多态事件和事件处理程序
- 事件系统:使用类型转换或联合进行继承
- 将函数名称传递给事件总线系统中的事件类
- SDL 2,如何使用事件系统和异步绘制
- 事件记录API未写入系统日志
- Qt中一个类似事件系统的信号/槽,没有分叉-C++
- 在C Linux中捕获系统事件
- C++事件系统-使用基于堆或堆栈的事件
- OSX-Qt应用程序在接收系统事件QEvent::FileOpen时崩溃
- 多线程事件系统
- 订阅windows系统事件本机c++
- 具有从 c++ 中的非模板基类派生的模板类的事件系统
- NodeJS 文件系统 监视抛出事件两次或更多次
- 从轮询切换到基于事件的系统
- 事件系统优化
- C++中的简单事件系统
- C++:游戏引擎的事件系统实现
- 如何在多监视器系统上检测最大化事件
- 嵌入式系统状态模式:存储与异步事件相关的信息
- 如何将系统事件从驱动程序发送到应用层