8

我有一个 C++ 库,它应该在多个线程上进行一些计算。我制作了独立的线程代码(即它们之间没有共享变量),除了一个数组。问题是,我不知道如何使它成为线程安全的。

我查看了互斥锁/解锁(QMutex,因为我正在使用 Qt ),但它不适合我的任务 - 虽然一个线程将锁定互斥锁,但其他线程将等待!

然后我读到了std::atomic,这看起来正是我所需要的。尽管如此,我还是尝试通过以下方式使用它:

std::vector<std::atomic<uint64_t>> *myVector;

它产生了编译器错误(使用已删除的函数 'std::atomic::atomic(const std::atomic&)')。然后我找到了解决方案- 为std::atomic. 我试过这个:

struct AtomicUInt64
{
    std::atomic<uint64_t> atomic;

    AtomicUInt64() : atomic() {}

    AtomicUInt64 ( std::atomic<uint64_t> a ) : atomic ( atomic.load() ) {}

    AtomicUInt64 ( AtomicUInt64 &auint64 ) : atomic ( auint64.atomic.load() ) {}

    AtomicUInt64 &operator= ( AtomicUInt64 &auint64 )
    {
                atomic.store ( auint64.atomic.load() );
    }
};

std::vector<AtomicUInt64> *myVector;

这个东西编译成功,但是当我无法填充向量时:

myVector = new std::vector<AtomicUInt64>();

for ( int x = 0; x < 100; ++x )
{
    /* This approach produces compiler error:
     * use of deleted function 'std::atomic<long long unsigned int>::atomic(const std::atomic<long long unsigned int>&)'
     */
    AtomicUInt64 value( std::atomic<uint64_t>( 0 ) ) ;
    myVector->push_back ( value );

    /* And this one produces the same error: */
    std::atomic<uint64_t> value1 ( 0 );
    myVector->push_back ( value1 );
}

我究竟做错了什么?我想我尝试了一切(也许不是,无论如何),但没有任何帮助。C++ 中的线程安全数组共享还有其他方法吗?

顺便说一句,我在 Windows 上使用 MinGW 32bit 4.7 编译器。

4

3 回答 3

6

AtomicUInt64这是您的类型的清理版本:

template<typename T>
struct MobileAtomic
{
  std::atomic<T> atomic;

  MobileAtomic() : atomic(T()) {}

  explicit MobileAtomic ( T const& v ) : atomic ( v ) {}
  explicit MobileAtomic ( std::atomic<T> const& a ) : atomic ( a.load() ) {}

  MobileAtomic ( MobileAtomic const&other ) : atomic( other.atomic.load() ) {}

  MobileAtomic& operator=( MobileAtomic const &other )
  {
    atomic.store( other.atomic.load() );
    return *this;
  }
};

typedef MobileAtomic<uint64_t> AtomicUInt64;

并使用:

AtomicUInt64 value;
myVector->push_back ( value );

或者:

AtomicUInt64 value(x);
myVector->push_back ( value );

您的问题是您std::atomic按值获取,这会导致副本被阻止。哦,你没能从operator=. 我还明确了一些构造函数,可能是不必要的。我添加const到您的复制构造函数中。

我也很想添加storeload方法来MobileAtomic转发到atomic.storeand atomic.load

于 2013-06-04T14:31:53.047 回答
2

您正在尝试复制不可复制的类型:AtomicUInt64构造函数采用atomic值。

如果您需要它可以从 初始化atomic,那么它应该通过 (const) 引用获取参数。但是,在您的情况下,您似乎根本不需要初始化atomic;为什么不初始化uint64_t呢?

还有几个小点:

  • 复制构造函数和赋值运算符应该通过const引用获取它们的值,以允许复制临时对象。

  • 分配向量new是一件相当奇怪的事情。您只是添加了额外的间接级别,没有任何好处。

  • 确保在其他线程可能正在访问它时从不调整数组的大小。

于 2013-06-04T14:16:23.690 回答
1

这条线

AtomicUInt64 ( std::atomic<uint64_t> a ) : atomic ( atomic.load() ) {}

您完全忽略了传入的参数,您可能希望它是 a.load() 并且您可能希望通过 const 引用获取元素,这样它们就不会被复制。

AtomicUInt64 (const std::atomic<uint64_t>& a) : atomic (a.load()) {}

至于你在做什么,我不确定它是否正确。数组内变量的修改将是原子的,但如果向量被修改或重新分配(这可能与push_back),那么没有什么可以保证您的数组修改将在线程之间工作并且是原子的。

于 2013-06-04T14:18:14.220 回答