libevent,动态添加或删除事件,无需更改事件循环
Posted
技术标签:
【中文标题】libevent,动态添加或删除事件,无需更改事件循环【英文标题】:Libevent, add or remove events dynamically without having to change the event loop 【发布时间】:2015-03-19 10:12:05 【问题描述】:我遇到的问题可能是对这句话真正含义的误解“应用程序只需要调用 event_dispatch(),然后动态添加或删除事件,而无需更改事件循环。”或者我找不到有关如何操作的正确文档。 好吧,问题是我认为我应该能够在使用 event_dispatch() 运行事件循环后将事件添加到事件循环中,但我无法让它工作。代码如下:
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <stdio.h>
static int n_calls = 0;
static int n_calls2 = 0;
void cb_func(evutil_socket_t fd, short what, void *arg)
struct event *me = arg;
printf("cb_func called %d times so far.\n", ++n_calls);
if (n_calls > 100)
event_del(me);
void cb_func2(evutil_socket_t fd, short what, void *arg)
struct event *me = arg;
printf("cb_func2 called %d times so far.\n", ++n_calls2);
if (n_calls2 > 100)
event_del(me);
int main(int argc, char const *argv[])
struct event_base *base;
enum event_method_feature f;
base = event_base_new();
if (!base)
puts("Couldn't get an event_base!");
else
printf("Using Libevent with backend method %s.",
event_base_get_method(base));
f = event_base_get_features(base);
if ((f & EV_FEATURE_ET))
printf(" Edge-triggered events are supported.");
if ((f & EV_FEATURE_O1))
printf(" O(1) event notification is supported.");
if ((f & EV_FEATURE_FDS))
printf(" All FD types are supported.");
puts("");
struct timeval one_sec = 1, 0 ;
struct timeval two_sec = 2, 0 ;
struct event *ev;
/* We're going to set up a repeating timer to get called called 100 times. */
ev = event_new(base, -1, EV_PERSIST, cb_func, NULL);
event_add(ev, &one_sec);
event_base_dispatch(base);
// This event (two_sec) is never fired if I add it after calling event_base_dispatch.
// If I add it before calling event_base_dispatch it works as the other event (one_sec) also does.
ev = event_new(base, -1, EV_PERSIST, cb_func2, NULL);
event_add(ev, &two_sec);
return 0;
【问题讨论】:
【参考方案1】:我现在看到了...我不知道为什么,但我认为事件循环开始在另一个线程或类似的东西中运行。我现在看到我试图做的事情毫无意义。您可以在回调中添加事件,即在循环运行时。当您启动事件循环时,它永远不会返回,因此之后的所有内容都不会被调用(除非您停止事件循环)
【讨论】:
以上是关于libevent,动态添加或删除事件,无需更改事件循环的主要内容,如果未能解决你的问题,请参考以下文章
使用 JavaScript 的 HTMLCollection 更改事件