- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试学习没有锁的并发。因此,我正在尝试为共享变量计数器实现简单的 Compare 和 Swap(cas)。我尝试创建 10 个线程,并希望使用 CAS 将每个线程的计数器值增加 1。因为 CAS 存储旧值并与当前值进行比较,并且仅在值未更改时更新。看[这里]我试图实现 CAS,但无法正确实现。 C++中计数器共享变量如何实现CAS?
#include <iostream>
#include <thread>
#include <unistd.h>
#include <atomic>
std::atomic<int> count = 0;
std::mutex n_mutux;
void increase_counter(int i)
{
int old_value = count.load() ;
while (!count.compare_exchange_weak(old_value, old_value +1))
{
}
}
int main() {
int thread_num =10;
std::thread t[thread_num];
for(int i=0;i<thread_num;i++)
{
t[i]=std::thread((increase_counter),i);
}
for(int i=0;i<thread_num;i++)
{
t[i].join();
}
std::cout<<count;
}
最佳答案
您的解决方案是正确的。
另一种方法是使用增量,参见 std::atomic::operator++()
或 fetch_add(1, std::memory_order_acq_rel)
.这两个不需要繁忙的等待循环。
std::atomic<int> count = 0
的初始化存在编译器错误.修复:
std::atomic<int> count{0};
稍微更高效的 CAS 是:
void increase_counter(int i) {
int old_value = count.load() ;
while(!count.compare_exchange_weak(old_value, old_value + 1,
std::memory_order_release,
std::memory_order_relaxed))
_mm_pause();
}
The
pause
intrinsic is used in spin-wait loops with the processors implementing dynamic execution (especially out-of-order execution). In the spin-wait loop, thepause
intrinsic improves the speed at which the code detects the release of the lock and provides especially significant performance gain.The execution of the next instruction is delayed for an implementation-specific amount of time. The
pause
instruction does not modify the architectural state. For dynamic scheduling, thepause
instruction reduces the penalty of exiting from the spin-loop.
参见 Benefitting Power and Performance Sleep Loops了解更多详情和基准。
关于c++ - 如何在 C++ 中为共享计数器实现简单的比较和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48802217/
我是一名优秀的程序员,十分优秀!