Hello! I have a C++ library based on Qt 5 that uses multiple threads (classes inherited from QThread) for some computations. I need to share a STL vector between them (threads don't perform any pushing/popping with this vector, but they change it's values). I use the special wrapper around std::atomic:

Qt Code:
  1. struct AtomicUInt64
  2. {
  3. std::atomic<uint64_t> atomic;
  4.  
  5. AtomicUInt64() : atomic ( uint64_t() ) {}
  6.  
  7. explicit AtomicUInt64 ( uint64_t const &v ) : atomic ( v ) {}
  8. explicit AtomicUInt64 ( std::atomic<uint64_t> const &a ) : atomic ( a.load() ) {}
  9.  
  10. AtomicUInt64 ( AtomicUInt64 const &other ) : atomic ( other.atomic.load() ) {}
  11.  
  12. AtomicUInt64 &operator= ( AtomicUInt64 const &other )
  13. {
  14. atomic.store ( other.atomic.load() );
  15. return *this;
  16. }
  17.  
  18. AtomicUInt64 operator++ ()
  19. {
  20. this->atomic++;
  21. return *this;
  22. }
  23. };
To copy to clipboard, switch view to plain text mode 

And std::vector in a data structure:

Qt Code:
  1. struct ThreadInput
  2. {
  3. std::vector<AtomicUInt64> *atomsUsed = NULL;
  4. //other variables
  5. };
To copy to clipboard, switch view to plain text mode 

I initialize this structure in a class that manages threads:

Qt Code:
  1. CalculationThread threadData;
  2. threadData.myVect = new std::vector<AtomicUInt64>();
  3. for ( int x = 0; x < 100; ++x )
  4. {
  5. AtomicUInt64 value ( 0 );
  6. threadData.myVect->push_back ( value );
  7. }
  8. //assign other variables in 'threadData'
  9. for ( int x = 0; x < 2; ++x )
  10. {
  11. MyThread *thread = new MyThread ( threadData );
  12. thread->start();
  13. }
To copy to clipboard, switch view to plain text mode 

Finally, this is MyThread's 'void run()' impementation:

Qt Code:
  1. void MyThread::run()
  2. {
  3. uint64_t ull;
  4. for ( ull = 0; ull < this->threadData.iterations; ++ull)
  5. {
  6. //increment the 100th value of 'myVect'
  7. ++this->threadInput.myVect->data()[99];
  8. }
  9. qDebug() << "Finished = " + QString::number(this->thredData.myVect->data()[99].atomic) + " | it = " + QString::number(ull);
  10. }
To copy to clipboard, switch view to plain text mode 

So, when I set 'threadData.iterations' variable to ~490000 (this value is different for different threads), I get the following in Application Output:

"Finished = 491760 | it = 249654"
"Finished = 499308 | it = 499308"

And this is not what I expected to see. Why the first finished thread outputs that the 100th value of vector is 249654? Shouldn't it be more than iteration count, as there were 2 threads?
Maybe there are another ways to share a STL vector between instances of `MyThread` class inherited from QThread and assume that it is atomic?