libevent的:它是允许释放它的回调函数内的事件是否由malloc创建事件 [英] libevent: is it allowed to free an event inside its callback function if the event is created by malloc

查看:490
本文介绍了libevent的:它是允许释放它的回调函数内的事件是否由malloc创建事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用的malloc 以创建事件,但我在一个亏损的地方释放他们,我想知道
是否允许释放事件的回调函数里面,这样的:

I need to create events using malloc, but I'm at a loss where to free them, I'm wondering whether it is allowed to free an event inside its callback function, like:

struct event *pkt_ev = (struct event *)malloc(sizeof(struct event));
evtimer_set(&pkt_ev, timer_cb, &pkt_ev);    
event_base_set(base, &pkt_ev); 
event_add(&pkt_ev, timeout);

回调函数timer_cb():

the callback function timer_cb():

    timer_cb(int fd, short ev, void* arg){
    .......
    free(arg);    // here the arg is &pkt_ev
}

我的初步想法是:回调函数后 timer_cb()被调用时,libevent的将隐式调用 event_del(安培; pkt_ev)。但自从我释放&放大器; pkt_ev 回调里面,将会有上崩溃/异常event_del(安培; pkt_ev)。是不是?

my initial thinking is: after the callback function timer_cb() is called, the libevent will implicitly call event_del(&pkt_ev). But since I freed &pkt_ev inside the callback, there will be a crash/exception on event_del(&pkt_ev). is it right?

但是,如果 event_del(安培; pkt_ev)不关心哪些内容 pkt_ev 点,它可能不会有什么问题?

however, if event_del(&pkt_ev) doesn't care what content pkt_ev points to, it might not be a problem?

,在这个函数:

        event_add(struct event *ev, struct timeval *timeout);

EV 指向的内容也应该得到了很多,一般应该是一个全局变量或它的使用寿命应包括事件循环(即,当事件循环函数运行时,它会访问由 EV )所指出的内容。如何有关超时指向的内容?应该指出的超时内容涵盖了事件循环?

the content pointed by ev should be cared a lot, generally it should be a global variable or its lifetime should cover the event loop(namely, when the event loop function is running, it will access the content pointed by ev). How about the content pointed by timeout? should the content pointed by timeout cover the event loop?

推荐答案

您第一个假设是错误的,libevent的隐式调用 event_del() 之前调用(鉴于EV_PERSIST标志没有被设置)后的回调函数,而不是。因此,有没有问题,在回调释放pkt_ev如果未设置EV_PERSIST标志。如果它被设置,你需要明确地调用 event_del()第一。

You first assumption is wrong, libevent implicitly calls event_del() before invoking the callback function, not after (given that the EV_PERSIST flag isn't set). So there is no issue freeing pkt_ev in a callback if the EV_PERSIST flag is not set. If it is set, you need to explicitely call event_del() first.

关于你的第二个问题,没有通过超时指向的内容前 event_add复制()的回报。

Regarding your second question, no, the content pointed by timeout is copied before event_add() returns.

这篇关于libevent的:它是允许释放它的回调函数内的事件是否由malloc创建事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆