libevent 多线程环境下 event_base_dispatch 无法跳出的问题

libevent 缺省情况下只支持在单个线程中使用。
最近遇到的一个问题,就是在2个线程中使用到 bufferevent_socket。
Thread1:
为了连接网络到服务器,用 event_base_new 创建 event_base,并有bufferevent_socket_new 创建bufferevent,并event_base_dispatch;
Thread2:
用到了 bufferevent_write,并在收不到服务器响应的时候,断开socket重新连接。其中涉及接收服务器的响应数据,如果长时间收不到,则断开连接。断开是用 event_base_loopbreak;

问题的表现:
当网络中断,比如wifi信号不稳、网线被意外拔掉等时候,按照预定设计,应该 event_base_loopbreak,跳出 event_base_dispatch,执行后续的重新建立网络连接 bufferevent_socket_connect。但是,实际上,往往会卡在 event_base_dispatch,event_base_loopbreak并没有使得 event_base_dispatch 跳出来。整个线程就卡在这里。造成服务器、客户端都不知道网络已经断了,即使网络恢复了,也没有恢复运行。

解决方法:
从2.x.x版本开始,libevent已经可以支持多线程使用:
下面一段摘自 libevent whatsnew-2.0.txt:
2.8. evthread_* functions for thread-safe structures.
Libevent structures can now be built with locking support. This code
makes it safe to add, remove, and activate events on an event base from a
different thread. (Previously, if you wanted to write multithreaded code
with Libevent, you could only an event_base or its events in one thread at
a time.)

If you want threading support and you’re using pthreads, you can just
call evthread_use_pthreads(). (You’ll need to link against the
libevent_pthreads library in addition to libevent_core. These functions are
not in libevent_core.)

If you want threading support and you’re using Windows, you can just
call evthread_use_windows_threads().

因此,linux环境下我们需要在 event_base_new 之前,调用一下 evthread_use_pthreads() 函数:

    #include <event2/thread.h>
    ......
    evthread_use_pthreads();
    struct event_base *ev_base = event_base_new();

这个函数在 libevent_pthreads.so 库中,因此连接选项除了 -levent 之外,还需要额外加上 -levent_pthreads。头文件是 libevent/include/event2/thread.h。

类似的,这个在windows环境下,应该是使用 evthread_use_windows_threads.

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值