简体   繁体   中英

Does libevent allow to run callback for timer/io in a different thread?

Due to some application reasons I need to run callback for timer/io events in a different thread.

Example:

void EventLoop::createIOEvent(int fd, short kind, event_cb originalCallback, void* originalUserData) 
{
    ...
    const auto data{std::make_shared<UserData>(originalUserData, originalCallback, callbackExecutor)};
    event* event{event_new(_eventBase, fd, kind, EventLoop::asyncCall, data.get())};
    event_add(event, nullptr);
    ...
}

void EventLoop::asyncCall(int fd, short kind, void* data)
{
    const auto userData{*(reinterpret_cast<UserData*>(data))};
    ExecutorWrapper(userData._callbackExecutor)
        .addRunnable([=]() {
            userData._originalCallback(fd, kind, userData._originalUserData);
    })
    .exec();
 }

Is it legal for libevent to use such approach?

Note: it seems that all works fine on Macos and iOS but on Android my test application just closes without any reasons.

Is it legal for libevent to use such approach?

So access to event/event_base can be done from multiple threads, in this case you need to enable threading support for libevent:

evthread_use_pthreads(); // or similar

And later use BEV_OPT_THREADSAFE for bufferevent thread-safety.

For more details take a look in the book .

And even though your approach should work after this modifications, it is not a good design choice. It will be way more better to create event workers (separate event_base + thread) and schedule your event ( event_add ) in the event_base of the background thread.

Android my test application just closes without any reasons.

Need details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM