Oliver
Oliver

Reputation: 98

Is boost::asio::io_service::post atomic?

Given a boost::asio::io_service io is it safe to call io.post(...) on threads other than the thread that started io.run()?

For example:

boost::asio::io_service io;

void f()
{
    /* do something */
    io.post(&f);
}

void g()
{
    /* do something else */
    io.post(&g)
 }

int main()
{
    std::thread t1(&f);
    std::thread t2(&g);

    io.run();

    t1.join();
    t2.join();

    return 0;
}

I assume that io_service uses some kind of internal data structure (e.g. a queue) and posting alters this data structure (e.g. pushing onto the queue). My concern is that the data structure may or may not be thread-safe.

I've searched around and haven't been able to find a straight answer to this question, although everything I've seen seems to indicate that post() is thread-safe (i.e. atomic). Can someone please verify?

Upvotes: 2

Views: 941

Answers (1)

Matthias247
Matthias247

Reputation: 10396

io_service::post is thread_safe, and posting from different threads is just fine (one often needs to do it in a multithreaded asio environment).

However your example has a bit of a race condition:

io.run() might complete, before the child threads have started running, and therefore before anything gets posted. If you want to avoid that it needs to run() until a specific stop condition (e.g. signaled from a posted handler) is met. io_service::work can help with that too.

Upvotes: 3

Related Questions