转载请注明出处:https://blog.csdn.net/shang3583091/article/details/109056835
最近在使用libevent的时候发现多线程调用bufferevent_write的时,在一段时间后经常会发送不出数据。后来在研究发现是默认情况下bufferevent是在主线程中使用的,多线程调用时线程不安全。
解决问题如下:
(1)直接添加“BEV_OPT_THREADSAFE”后创建bufferevent不成功问题
(2)添加evthread_use_pthreads()方法后编译时提示:“evthread_use_pthreads 未定义的引用”的问题
(3)多线程调用发送消息后经常出现发现不出数据的问题
具体解决方法如下:
1:准备工作
在我的cmake文件中需要添加“-levent_pthreads”选项,不然会报“evthread_use_pthreads 未定义的引用”,然后在代码中添加“#include <event2/thread.h>”的引用
2:添加evthread_use_pthreads方法
添加下面的方法,linux中调用“evthread_use_pthreads”,windows中会调用“evthread_use_windows_threads”
#ifdef WIN32
evthread_use_windows_threads();//win上设置
#else
evthread_use_pthreads();//unix上设置
#endif
注意:一定要在“event_base_new”之前添加此方法!
3:添加“BEV_OPT_THREADSAFE”选项
此选项会自动为bufferevent分配锁,这样就可以安全地在多个线程中使用bufferevent。
代码如下:
bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
完成以上三步后即可解决问题!