【发布时间】:2023-03-25 12:40:01
【问题描述】:
我正在尝试使用 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 ;
}
【问题讨论】:
-
我们不了解您的硬件,但
memory_order_relaxed并不是最便携的选择。它肯定会在某些类型的 CPU 上给出不一致的结果。
标签: c++ linux atomic boost-thread race-condition