I have a C ++ library that needs to do some calculations on multiple threads. I created independent code for the threads (i.e. there are no common variables between them), with the exception of one array. The problem is that I do not know how to make it thread safe.
I looked at locking / unlocking mutex ( QMutex , since I use Qt), but it is not suitable for my task - while one thread blocks the mutex, other threads will wait!
Then I read about std::atomic , which looked exactly as I needed. However, I tried using it as follows:
std::vector<std::atomic<uint64_t>> *myVector;
And he produced a compiler error (using the remote function 'std :: atomic :: atomic (const std :: atomic &)'). Then I found a solution - use a special shell for std::atomic . I tried this:
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;
This thing compiles successfully, but when I cannot fill the vector:
myVector = new std::vector<AtomicUInt64>(); for ( int x = 0; x < 100; ++x ) { AtomicUInt64 value( std::atomic<uint64_t>( 0 ) ) ; myVector->push_back ( value ); std::atomic<uint64_t> value1 ( 0 ); myVector->push_back ( value1 ); }
What am I doing wrong? I guess I tried everything (maybe not, one way or another) and nothing helped. Are there any other ways for threaded access to an array in C ++?
By the way, I am using the MinGW 32bit 4.7 compiler on Windows.
source share