繁体   English   中英

同时使用非原子和原子操作

[英]Use non-atomic and atomic operations at the same time

我有一个线程池,每个线程包含一个计数器(基本上是TLS)。

需要主线程通过计算所有线程局部计数器的总和来频繁更新。

大多数情况下,每个线程都会增加自己的计数器,因此不需要同步。

但是在主线程更新的时候,我当然需要某种同步。

我想出了MSVS内在函数( _InterlockedXXX函数),它表现出了很好的性能(在我的测试中大约0.8秒)然而,它限制了我的代码到MSVC编译器和X86 / AMD64平台,但是有一种C ++ - 可移植的方式来实现它?

  • 我尝试将计数器的int类型更改为std::atomic<int> ,使用std::memory_order_relaxed进行递增,但此解决方案非常慢! (~4s)

  • 当使用基本成员std::atomic<T>::_My_val ,我会按照我想要的方式非原子地访问该值,但它也不可移植,所以问题是相同的......

  • 使用由所有线程共享的单个std::atomic<int>甚至更慢,因为高争用(~10 s)

你有什么想法吗? 也许我应该使用库(boost)? 还是写我自己的课?

std::atomic<int>::fetch_add(1, std::memory_order_relaxed)_InterlockedIncrement一样快。

Visual Studio编译前者以lock add $1 (或等效物),后者编译lock inc ,但执行时间没有差别; 在我的系统(Core i5 @ 3.30 GHz)上,每个采用5630 ps / op,大约18.5个周期。

使用Benchpress的 Microbenchmark:

#define BENCHPRESS_CONFIG_MAIN
#include "benchpress/benchpress.hpp"
#include <atomic>
#include <intrin.h>

std::atomic<long> counter;
void f1(std::atomic<long>& counter) { counter.fetch_add(1, std::memory_order_relaxed); }
void f2(std::atomic<long>& counter) { _InterlockedIncrement((long*)&counter); }
BENCHMARK("fetch_add_1", [](benchpress::context* ctx) {
    auto& c = counter; for (size_t i = 0; i < ctx->num_iterations(); ++i) { f1(c); }
})
BENCHMARK("intrin", [](benchpress::context* ctx) {
    auto& c = counter; for (size_t i = 0; i < ctx->num_iterations(); ++i) { f2(c); }
})

输出:

fetch_add_1                           200000000        5634 ps/op
intrin                                200000000        5637 ps/op

我提出了适合我的这种实现方式。 但是,我找不到编码semi_atomic<T>::Set()

#include <atomic>

template <class T>
class semi_atomic<T> {
    T Val;
    std::atomic<T> AtomicVal;
    semi_atomic<T>() : Val(0), AtomicVal(0) {}
    // Increment has no need for synchronization.
    inline T Increment() {
        return ++Val;
    }
    // Store the non-atomic Value atomically and return it.
    inline T Get() {
        AtomicVal.store(Val, std::memory_order::memory_order_release);
        return AtomicVal.load(std::memory_order::memory_order_relaxed);
    }
    // Load _Val into Val, but in an atomic way (?)
    inline void Set(T _Val) {
        _InterlockedExchange((volatile long*)&Val, _Val); // And with C++11 ??
    }
}

谢谢你,告诉我是否有问题!

你肯定是对的:每个线程都需要一个std::atomic<int>来实现可移植性,即使它在某种程度上很慢。

但是,在X86和AMD64架构的情况下,它可以(非常)优化。

下面是我得到了什么, sInt是一个签署32位或64位。

// Here's the magic
inline sInt MyInt::GetValue() {
    return *(volatile sInt*)&Value;
}

// Interlocked intrinsic is atomic
inline void MyInt::SetValue(sInt _Value) {
#ifdef _M_IX86
    _InterlockedExchange((volatile sInt *)&Value, _Value);
#else
    _InterlockedExchange64((volatile sInt *)&Value, _Value);
#endif
}

此代码将在具有X86体系结构的MSVS中运行( GetValue()需要)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM