gpt4 book ai didi

c++ - 如何在 C++ 中为共享计数器实现简单的比较和交换

转载 作者:行者123 更新时间:2023-11-30 01:37:57 31 4
gpt4 key购买 nike

我正在尝试学习没有锁的并发。因此,我正在尝试为共享变量计数器实现简单的 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();
}

Pause Intrinsic :

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, the pause 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, the pause 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com