我的libevent计时器在另一个事件发生时立即停止.这正常吗?

My libevent timer stops as soon as another event occurs... is that normal?

本文关键字:常吗 计时器 libevent 另一个 事件 我的      更新时间:2023-10-16

目前我设置了两个事件:

  • 监听来自客户端的新连接(我是服务器)
  • 一个计时器,每秒运行一些代码来做各种后台工作

在启动时定时器工作,我可以等待只要我想,我的回调被一次又一次地调用,每秒钟就像预期的。

然而,一旦我得到一个客户端连接,另一个甚至发生,不知何故定时器停止工作。libevent接口中是否存在已知的错误,或者我是否可能滥用库?

我使用的libevent版本libevent-2.0-5:amd64在Ubuntu 14.04.

我添加了自己的c++接口,所以在这里显示所有的代码会非常大。可以在SourceForge.net的项目中浏览:

https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/lib/snap_communicator.hhttps://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/lib/snap_communicator.cpp

的用法非常简单,但是它又非常大,完整的实现在这里:

https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/lib/snapwebsites.cpp

重要的部分是这样的:

g_connection = new connection_t;
g_connection->f_communicator.reset(new snap_communicator(priority));
g_connection->f_listener.reset(new listener_impl(this, host[0].toUtf8().data(), p, max_pending_connections, true, false));
g_connection->f_listener->set_name("server listener");
g_connection->f_communicator->add_connection(g_connection->f_listener);
g_connection->f_temporary_timer.reset(new temporary_timer(this));
g_connection->f_temporary_timer->set_name("server timer");
g_connection->f_communicator->add_connection(g_connection->f_temporary_timer);
g_connection->f_communicator->run();

正如我们所看到的,我添加了这两个"连接",计时器工作得很好,直到侦听器发生。只有一个地方,我从libevent对象中删除了这两个连接,它没有命中(我知道我有一个日志,是的,日志记录器工作得很好。)

我错了!文档明确指出,您应该使套接字非阻塞。一旦我这样做了,它就开始像预期的那样工作了。

我的套接字阻塞之前,因为我只是调用accept()

现在我真的不明白为什么库有这样的限制,但这是解决这个问题的方法。

我为监听器添加了以下代码:

if(get_socket() != -1)
{
    // libevent does not like blocking sockets...
    int optval(1);
    ioctl(get_socket(), FIONBIO, &optval);
}