Are event_base_loop and event_base_dispatch thread safe?

371 Views Asked by At

Are the event_base_loop()(publisher thread) and event_base_dispatch()(subscriber thread) functions thread safe? Recently I checked my application for any synchronization errors using valgrind's helgrind tool. In the report it's mentioned that there exists a race condition between event_base_loop() and event_base_dispatch() even though both these functions are called with different struct event_base variables (struct event_base base_pub(publisher thread) and struct event_base base_sub (subscriber thread)). Below is the sample code

Publisher Thread

struct event_base base_pub = event_base_new();
while (true) {
    ... // publish data
    event_base_loop(base_pub, EVLOOP_NONBLOCK);
    sleep(1);
    ...
}

Subscriber Thread

struct event_base base_sub = event_base_new();
while (true) {
    ... // register subscriber callback function
    event_base_dispatch(base_sub);
    ...
}
1

There are 1 best solutions below

0
user1095108 On

They are thread-safe, if you enable locking/condition variables through:

evthread_use_pthreads();

You also need to link with libevent_pthreads. Note that:

Before you call any other Libevent functions, you need to set up the library. If you're going to use Libevent from multiple threads in a multithreaded application, you need to initialize thread support – typically by using evthread_use_pthreads() or evthread_use_windows_threads().

Currently, only one thread can be dispatching a given event_base at a time. If you want to run events in multiple threads at once, you can either have a single event_base whose events add work to a work queue, or you can create multiple event_base objects.