c++ - std::atomic_bool 标志的内存顺序

标签 c++ multithreading atomic memory-model

我正在阅读 Anthony Williams 的“C++ Concurrency in Action”,我看到了这段代码,它是线程池的简单实现。

class thread_pool
{
    std::atomic_bool done;
    thread_safe_queue<std::function<void()> > work_queue;
    std::vector<std::thread> threads;
    join_threads joiner;

    void worker_thread()
    {
        while(!done) 
        {
            std::function<void()> task;
            if(work_queue.try_pop(task))            
            {
                task(); 
            }
            else
            {
                std::this_thread::yield();
            }
       }
    }
    public:
    thread_pool():
        done(false),joiner(threads)
    {
        unsigned const thread_count=std::thread::hardware_concurrency();
        try 
        {

           for(unsigned i=0;i<thread_count;++i)
           {
              threads.push_back(
                 std::thread(&thread_pool::worker_thread,this));
           } 
        }
        catch(...)
        {
           done=true;
           throw;
        }
     }

    ~thread_pool()
    {
        done=true;
    }

    template<typename FunctionType>
    void submit(FunctionType f)
    {
        work_queue.push(std::function<void()>(f));
    }
};

附言join_threads 是一个简单的类,它在销毁和 thread_safe_queue 是一个……线程安全队列!

我的问题是关于 bool 标志 std::atomic_bool done。我读到使用默认赋值运算符与使用顺序一致的内存排序是一样的。

完成=真。 -> done.store(true, std::memory_order_seq_cst)

在这种情况下真的有必要吗?使用发布/获取排序 甚至宽松 排序还不够吗? 工作线程只是在 bool 值上循环,显然没有任何其他内存访问可以与之同步。

我是否过度优化或遗漏了什么?

最佳答案

我想你没有误解。顺序一致的访问比最低要求更受限制。

在这种情况下,使用 std::atomic::operator= 具有简单的优点(即更清晰的代码),并且不太可能引入任何性能问题 - 特别是在大多数情况下平台,原子 bool 值非常紧密地映射到处理器操作。

关于c++ - std::atomic_bool 标志的内存顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30302013/

相关文章:

c# - 写/读什么时候影响主存?

java - AtomicInteger.compareAndSet 返回原始值,而不是 boolean 值

c++ - 同步 1 个生产者和 1 个以上的消费者(多线程)

c++ - 状态模式 C++

c++ - 父进程中子进程的数量 C/C++, LINUX

ios - 原子读/写 int 值 w/o 对 int 值本身的额外操作

c++ - OpenCV Mat 在 push_back 时崩溃

c++ - 在 PThreads 或 Windows 中线程退出时调用函数

c++ - 这个用于原子浮点的 C++ 实现安全吗?

iphone - 以原子方式将 NSString 追加到文件中?