我有一个 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 编译器。