什么时候应该使用 std::atomic 而不是 std::mutex?

问题描述 投票:0回答:1

在问题如何使用std::atomic<>中,显然我们可以使用

std::mutex
来保持线程安全。我想知道什么时候使用哪一个。

struct A {
    std::atomic<int> x{0};
    void Add() {
        x++;
    }
    void Sub() {
        x--;
    }
};

std::mutex mtx;
struct A {
    int x = 0;
    void Add() {
        std::lock_guard<std::mutex> guard(mtx);
        x++;
    }
    void Sub() {
        std::lock_guard<std::mutex> guard(mtx);
        x--;
    }     
};
multithreading c++11 thread-safety mutex stdatomic
1个回答
9
投票

根据经验,对 POD 类型使用

std::atomic
,其中底层专业化将能够使用一些聪明的东西,例如 CPU 上的总线锁(这不会给你带来比管道转储更多的开销),甚至是旋转锁。在某些系统上,
int
可能已经是原子的,因此
std::atomic<int>
将有效地专门化为
int

对非 POD 类型使用

std::mutex
,请记住获取互斥量至少比总线锁慢一个数量级。

如果您仍然不确定,请测量性能。

© www.soinside.com 2019 - 2024. All rights reserved.