[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[Libevent-users] How to avoid calling bufferevent_write on a freed bev efficiently?



Hi, all,

    I'm using libevent for my project. But I can't find an easy way to
    make sure a bufferevent structure is still legal when I want to
    call bufferevent_write to send some info back to client.

    In my project, the event_base_dispatch() runs in main thread, and
    when it receives some packets from a client, a structure Message
    is constructed and pushed to a message queue. There is a thread
    pool, and each thread fetches Message out from the queue, then
    processes them, and sends some info back to clients. Structure
    Message records the bufferevent that it comes from, so in those
    processing threads, I call bufferevent_write to send info
    back. (Hope I make this clear).

    But the client may close the connection, which results in that
    bufferevent structure is freed in event call back function (main
    thread). This results in crash in processing-threads when they try
    to send info back using a freed bufferevent.

    The way I use is putting bufferevent_free and
    bufferevent_write in a critical section (a global lock), and

    - when there is a connection established, record the newly created
      bufferevent (say a set)
    - in the critical section of bufferevent_free, delete that bev
      from that set
    - in the critical section of bufferevent_write, check whether that
      bev is in that set, if so call bufferevent_write

    But I think maybe this is not efficient, is there an easy way in
    libevent? Does bufferevent_lock/bufferent_unlock help?

Thanks and Regards,
Wenliang