我有一个C++库,它应该在多个线程上进行计算。我编写了独立的线程代码(即它们之间没有共享变量),除了一个数组。问题是,我不知道如何使其线程安全。
我查看了互斥锁/解锁(使用Qt的QMutex),但它不适用于我的任务-当一个线程锁定互斥锁时,其他线程将等待!
然后我了解了std::atomic,这看起来正是我所需要的。尽管如此,我尝试以以下方式使用它:
这个东西编译成功了,但是我无法填充向量:
我查看了互斥锁/解锁(使用Qt的QMutex),但它不适用于我的任务-当一个线程锁定互斥锁时,其他线程将等待!
然后我了解了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编译器。
push_back
的情况下初始化std::vector
?抱歉问这样愚蠢的问题,但我除了std::vector t = { 0, 0, 0 }
之外什么都不知道——而且这种方法在大量项目时显然是无用的。 - ahawkthomas