Is it possible to create an atomic vector or array in C++?

rainbow picture rainbow · Sep 6, 2017 · Viewed 15.7k times · Source

I have some code which uses an array of int (int[]) in a thread which is activated every second.

I use lock() from std::mutex to lock this array in this thread.

However I wonder if there is a way to create an atomic array (or vector) to avoid using a mutex? I tried a couple of ways, but the compiler always complains somehow?

I know there is a way to create an array of atomics but this is not the same.

Answer

In practice, at the CPU level, there are instructions which can atomically update an int, and a good compiler will use these for std::atomic<int>. In contrast, there are are no instructions which can atomically update a vector of ints (for any architecture I am aware of), so there has got to be a mutex of some sort somewhere. You might as well let it be your mutex.


For future readers who haven't yet written code with the mutex:

You can't create a std::atomic of int[10], because that leads to a function which returns an array - and you can't have those. What you can do, is have a std::atomic<std::array<int,10>>

int main()
{
  std::atomic<std::array<int,10>> myArray;
}

Note that the compiler/library will create a mutex under the hood to make this atomic. Note further that this doesn't do what you want. It allows you to set the value of the whole array atomically.

It doesn't allow you to read the whole array, update one element, and write the whole array back atomically.

The reads and the writes will be individually atomic, but another thread can get in between the read and the write.

You need the mutex!