c++ - 如何使用 boost atomic 来消除竞争条件?

标签 c++ linux atomic boost-thread race-condition

我正在尝试使用 boost::atomic 在 Linux 上进行多线程同步。

但是,结果并不一致。

任何帮助将不胜感激。

谢谢

#include <boost/bind.hpp>
#include <boost/threadpool.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
#include <boost/atomic.hpp>

boost::atomic<int> g(0) ;

void f()
{

    g.fetch_add(1, boost::memory_order_relaxed);

    return ;
 }
 const int threadnum = 10;
 int main()
 {
    boost::threadpool::fifo_pool tp(threadnum);
    for (int i = 0 ; i < threadnum ; ++i)
            tp.schedule(boost::bind(f));
    tp.wait();
    std::cout << g << std::endl ;
    return 0 ;
  }

最佳答案

我并不特别熟悉 boost 线程库,或者 boost::threadpool,但在我看来,当您访问 g 的值时,线程不一定已完成,因此您会得到介于 0 和10.

这是您的程序,已修改为使用标准库,并插入了连接,以便获取添加发生在 g 的输出之前。

std::atomic<int> g(0);

void f() {
    g.fetch_add(1, std::memory_order_relaxed);
}

int main() {
    const int threadnum = 10;
    std::vector<std::thread> v;

    for (int i = 0 ; i < threadnum ; ++i)
        v.push_back(std::thread(f));

    for (auto &th : v)
        th.join();

    std::cout << g << '\n';
}

编辑:

如果您的程序即使添加了 tp.wait() 仍然不一致,那就令人费解了。添加应该在线程结束之前发生,我认为线程结束将与 tp.wait() 同步,这发生在读取之前。所以所有的添加都应该在打印 g 之前发生,即使你使用 memory_order_relaxed,所以打印的值应该是 10。

关于c++ - 如何使用 boost atomic 来消除竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10966528/

相关文章:

c++ - C++11 atomic<T> 可以与 mmap 一起使用吗?

python - 变量交换是否保证在python中是原子的?

c++ - 模板(元)编程是否总是只有一种实现方式?

c++ - Qt 应用程序在声明新对象后崩溃

c++ - 在 C++ 的面向对象设计中,在哪里声明共享变量?

linux - 无法从在另一个 docker 容器中运行的服务器连接到在 docker 中运行的 Postgis

android - 无法检测adb版本,adb

c++ - 在 Linux 上计时共享库加载时间

linux - 找出导致机器重启的原因

REST API : How to ensure atomicity?