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

Re: [Libevent-users] Add multiples bufferevents on one base then lead to some errors.



On Wed, Mar 23, 2016 at 09:56:56PM -0400, Tim Chou wrote:
> The listener indeed helps me to reduce the coding efforts. However, what I
> want to do is still not working.
> 
> Is it possible to bind several connections to a base and dispatch event of
> the base in a new thread?
> So I use main function to accept the connection and add this fd to a base
> running in another thread?

Yep, you can use buffevent_base_set(), but be aware since it may fail,
but this must work almost always:

int buffevent_change_base(struct buffevent *bufev, struct event_base *base)
{
    short flags = bufferevent_get_enabled(bufev);
    buffevent_disable(bufev, flags);
    int ret = bufferevent_base_set(bufev, new_base);
    bufferevent_enable(bufev, flags);
    return ret;
}

But better solution is to pass client fd (via pipe/socketpair) just
after accept() to another thread, here are some examples:
- cpp
  https://github.com/azat/boostcache/blob/libevent-aio/src/kernel/net/commandserver.cpp#L76  -- pass client fd to thread
  https://github.com/azat/boostcache/blob/libevent-aio/src/kernel/net/commandserver.cpp#L199 -- handle client fd in thread
- c
  https://github.com/ellzey/libevhtp/blob/develop/evthr.c#L331
  https://github.com/ellzey/libevhtp/blob/develop/evhtp.c#L2184

> >>   bev = malloc(sizeof(struct bufferevent));
> >>   bev = bufferevent_socket_new(evbase, client_fd, BEV_OPT_CLOSE_ON_FREE);

bufferevent_socket_new() already do malloc() you don't need it,
otherwise it will leak.
***********************************************************************
To unsubscribe, send an e-mail to majordomo@xxxxxxxxxxxxx with
unsubscribe libevent-users    in the body.