简体   繁体   English

boost :: asio :: io_service :: post原子了吗?

[英]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() ? 给定boost::asio::io_service io ,可以安全地在启动io.run()的线程之外的其他线程上调用io.post(...) 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 (eg a queue) and posting alters this data structure (eg pushing onto the queue). 我假设io_service使用某种内部数据结构(例如队列),并且发布会更改此数据结构(例如推入队列)。 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 (ie atomic). 尽管我所看到的一切似乎都表明post()是线程安全的(即原子的),但我四处搜寻并无法找到该问题的直接答案。 Can someone please verify? 有人可以验证吗?

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). io_service::post是thread_safe,并且从不同线程进行发布就可以了(通常需要在多线程asio环境中执行此操作)。

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. io.run()可能在子线程开始运行之前完成,因此在发布任何内容之前都已完成。 If you want to avoid that it needs to run() until a specific stop condition (eg signaled from a posted handler) is met. 如果要避免这种情况,则需要运行run()直到满足特定的停止条件(例如,从发布的处理程序发出信号)。 io_service::work can help with that too. io_service::work也可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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