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

Re: [Libevent-users] bufferevent_pair in multithreaded application



On Wed, Aug 17, 2016 at 11:50:43AM +0200, Jan Heylen wrote:
> Hi,

Hi,

> I've got following use case:
> in a multithreaded application:
> some threads are running in an eventloop (with a event_base)
> some thread are not, the just run as pthreads with 'while(1)' or a
> 'select/epoll' on a set of fds

bufferevent_pair doesn't have any fd there, so you can't monitor it in
different threads,

> In order to communicate between these threads, in a memory safe and
> clean locking manner, I was thinking on using a bufferevent_pair
> between such an eventloop thread and a 'pthread' thread.
> 
> Questions:
> * If I understand it correctly, the bufferevent pair would be created
> and handled by the eventloop_thread, and the pthread thread can write
> and read to one of the bufferevent buffers in the pair. Is this
> correct? Is this use case a way you can use bufferevent pairs?

But yes bufferevent_pair will be handler with event loop, but using
deferred callbacks (so this is kind of emulation in this case).

> * in the pthread (the 'other' thread), is there a way to
> 'select/poll/epoll' on a fd of this buffer (or read/write events on
> this buffer), without using libevent/eventloop? Or how would this be
> used (busy poll loop like in the example below not taking into
> account), Or do you need to create a separate pipe (e.g.) to trigger
> the pthread (which not using libevent besides the bufferevent_write

Of course you can do busy loop like in your sample, but it is better to
use socketpair() + regular bufferevent event here, because in this case
you will have fd that you can monitor in different base, and this means
you can poll them with libevent, and of course you can do this in
different threads (and you can yosue EVLOOP_ONCE for this, i.e. to
avoid running event loop every time, since I guess that threads should
do something).

So something like this should work:
    evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair);

    bev1 = bufferevent_socket_new(base1, pair[0], 0);
    bev2 = bufferevent_socket_new(base2, pair[1], 0);

    bufferevent_disable(bev1, EV_READ);
    bufferevent_enable(bev2, EV_READ);

    bufferevent_setcb(bev1, NULL, writecb, errorcb, NULL);
    bufferevent_setcb(bev2, readcb, NULL, errorcb, NULL);


Cheers,
Azat.
***********************************************************************
To unsubscribe, send an e-mail to majordomo@xxxxxxxxxxxxx with
unsubscribe libevent-users    in the body.