V1.4版之前只有一个库libevent,它包含现在分散到libevent_core和libevent_extra中的所有功能。
V2.0版之前不支持锁:只有确定不同时在多个线程中使用同一个结构体时,libevent才是线程安全的。
event_core.lib 包含了libevent的基本功能,例如事件循环、事件信号、定时器等。
event_extra.lib 包含了libevent的扩展功能,例如缓冲I/O、HTTP服务器和客户端、DNS解析等。
Linux编译安装
./autogen.sh (sudo yum install automake autoconf libtool)
./configure
./configure --prefix=/usr --libdir=/usr/lib64
libevent-release-2.0.21-stable编译报错,到下一个版本libevent-release-2.0.22-stable就可以了
默认./configure会安装到/usr/local/lib,需要把/usr/local/lib 加到/etc/ld.so.conf中,然后sudo ldconfig -v生效
Linux程序运行时找不到动态库的解决方法_相对路径可以找到动态库,绝对路径找不到动态库-CSDN博客
windows下编译
使用nmake方式 https://www.cnblogs.com/BroccoliFighter/p/17901283.html
1、error 未定义UINT32_WIN
WIN32-Code/nmake/event2/event-config.h
/* #define EVENT__HAVE_STDINT_H_1 */
2. error LNK2019: 无法解析的外部符号 __imp_if_nametoindex,函数 evutil_inet_pton_scope...
解决办法: 在test/Makefile.nmake里面找到:
LIBS=..\libevent.lib ws2_32.lib shell32.lib advapi32.lib
在后面添加 Iphlpapi.lib库:修改如下:
LIBS=..\libevent.lib ws2_32.lib shell32.lib advapi32.lib Iphlpapi.lib
使用
多线程
windows下引用 event.lib ws2_32.lib Iphlpapi.lib
Linux下加 event_pthreads.so 编译的时候 ./configure --with-event-pthreads (好像没有加也能编译出来)
#include <event2/thread.h>
#ifdef WIN32
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
#ifdef WIN32
WSACleanup();
#endif
定时任务
注意: 在定时任务处理函数中,一定要再event_add(timer_event,&tv);否则event_base_dispatch(base);会立刻退出
#include <stdio.h>
#include <stdlib.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/thread.h>
struct event_base *base;
#ifdef WIN32
#ifdef _DEBUG
#include <string>
using namespace std;
string GetCurrentTimeString()
{
time_t now = time(NULL);
struct tm* tmVar = localtime(&now);
char timeBuff[32] = { '\0' };
sprintf(timeBuff, "%04d-%02d-%02d %02d:%02d:%02d",
tmVar->tm_year + 1900, tmVar->tm_mon + 1, tmVar->tm_mday,
tmVar->tm_hour, tmVar->tm_min, tmVar->tm_sec);
string cstrTime(timeBuff);
return cstrTime;
}
#endif
#endif
//日志处理回调函数
void log_act(evutil_socket_t listener, short event, void *arg);
int main()
{
#ifdef WIN32
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
struct event* timer_event;
struct timeval tv; //定时器
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
base = event_base_new();
if (!base)
{
return -1;
}
tv.tv_sec = 0;
tv.tv_usec = 1000;
timer_event = event_new(base, -1, EV_TIMEOUT,log_act,event_self_cbarg());
event_add(timer_event,&tv);
event_base_dispatch(base);
#ifdef WIN32
WSACleanup();
#endif
return 0;
}
//日志处理回调函数
void log_act(evutil_socket_t listener, short event, void *arg)
{
struct event *timer_event = (struct event*)arg;
struct timeval tv; //定时器
string strNow = GetCurrentTimeStr();
printf("------------------%s-event act\n", strNow.c_str());
event_add(timer_event,&tv);
return;
}
4872




被折叠的 条评论
为什么被折叠?



