how to use std::atomic<>
在上面的问题中,显然我们可以使用 std::mutex
以保持线程安全。我想知道什么时候用哪个。
classs A
{
std::atomic<int> x;
public:
A()
{
x=0;
}
void Add()
{
x++;
}
void Sub()
{
x--;
}
};
和
std::mutex mtx;
classs A
{
int x;
public:
A()
{
x=0;
}
void Add()
{
std::lock_guard<std::mutex> guard(mtx);
x++;
}
void Sub()
{
std::lock_guard<std::mutex> guard(mtx);
x--;
}
};
最佳答案
根据经验,使用 std::atomic
对于 POD 类型,底层特化将能够使用一些聪明的东西,比如 CPU 上的总线锁(它不会给你带来比管道转储更多的开销),甚至是自旋锁。在某些系统上,int
可能已经是原子的,所以 std::atomic<int>
将有效地专注于 int
.
使用 std::mutex
对于非 POD 类型,请记住获取互斥锁至少比总线锁慢一个数量级。
如果您仍然不确定,请测量性能。
关于multithreading - std::atomic 和 std::mutex 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39617208/