gpt4 book ai didi

c++ - C++ 中的低延迟回调

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:56 25 4
gpt4 key购买 nike

我有一个事件驱动的应用程序。我想保持事件处理程序(EventHandler 类能够处理许多/所有事件)的通用实现 - 同时允许 EventSource 可变(特别是 - 在编译时)。

为了将 EventHandlerEventSource 相结合,我必须在 EventSource 中存储一个 handler 实例>。我尝试存储各种形式的处理程序:

  • 指向 EventHandler 接口(interface)的指针(具有在具体 EventHandler 中定义的公共(public)处理程序方法
  • std::function 的实例 - 这提供了最大的灵 active

然而,在这两种情况下,调用目标方法/lambda 的延迟都非常高(在我的测试设置中约为 250ns)——更糟糕的是,不一致。可能是由于虚拟表和/或堆分配和/或类型删除导致的???

为了减少这种延迟,我想使用模板。

我能想到的最好的是:

template <typename EventHandler>
class EventSource1
{
EventHandler* mHandler;
public:
typedef EventHandler EventHandlerType;

void AssignHandler (EventHandler* handler)
{
this->mHandler = handler;
}

void EventuallyDoCallback (int arbArg)
{
this->mHandler->CallbackFunction (arbArg);
}
};

template <EventSourceType>
class EventSourceTraits
{
typedef EventSourceType::EventHandlerType EventHandlerType;
static void AssignHandler (EventSourceType& source, EventHandlerType* handler)
{
source.AssignHandler(handler);
}
};

class EventHandler
{
public:
void CallbackFunction (int arg)
{
std::cout << "My callback called\n";
}
};


int main ()
{
EventSource1<EventHandler> source; /// as one can notice, EventSource's need not to know the event handler objects.
EventHandler handler;

EventSourceTraits<EventSource1>::AssignHandler (source, &handler);
}

此方法施加了一个限制,即我的所有 EventSource 都是模板类。

问题是:这是实现一致且低延迟回调的最佳方式吗?是否可以改进此代码以避免事件源类完全独立于事件处理程序对象的类型?

最佳答案

Is this best way to achieve consistent and low latency to callback?

正如问题评论中所建议的,我宁愿尝试并衡量以了解这是否真的是一个问题,以及什么是最适合您的选择。
不存在最好的方法,主要取决于实际问题。

can this code be improved to avoid the event source classes be completely independent of event handler objects' type ?

也许以下是开始实现这一目标的好点:

#include <iostream>

class EventSource1
{
using invoke_t = void(*)(void *C, int value);

template<typename T, void(T::*M)(int)>
static void proto(void *C, int value) {
(static_cast<T*>(C)->*M)(value);
}

invoke_t invoke;
void *handler;

public:
template<typename T, void(T::*M)(int) = &T::CallbackFunction>
void AssignHandler (T* ref)
{
invoke = &proto<T, M>;
handler = ref;
}

void EventuallyDoCallback (int arg)
{
invoke(handler, arg);
}
};

class EventHandler
{
public:
void CallbackFunction (int arg)
{
std::cout << "My callback called: " << arg << std::endl;
}
};

int main ()
{
EventSource1 source;
EventHandler handler;

source.AssignHandler(&handler);
source.EventuallyDoCallback(42);
}

查看 wandbox .

关于c++ - C++ 中的低延迟回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42083238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com