Germán Diago
Germán Diago

Reputation: 7673

Getting data from array written from another thread

I have the following situation.

I have a thread that writes to an array. After writing to that array I need to read that array. Reading happens after writing the array and I can guarantee so through another means (this would imply I will not need condition variables, but just when reading "refreshing" contents of the array). The array is read later from another thread.

EDIT: Additionally, the writing will happen at different times, the array is not written all at once.

I need to read the full contents of the array with all entries already refreshed and with the actual values at the time of reading. Right now the values are not refreshed.

What is the best way to synchronize this?

I am not sure how I would do it. I do know for a single variable a mutex would be enough, but this is an array. I am not sure what the correct way to do this is. I am not sure how to do it: a lock?

Upvotes: 1

Views: 801

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136515

There is a fundamental issue that an array cannot be written to and read atomically. Without blocking the writer and the reader may race, so that the reader may observe a partially updated array.

One solution would be to use a single-producer-single-consumer ring-buffer with elements being pointers to those arrays. This way the writer and the reader do not race writing/reading the same array and the reader only ever observes consistent data.

Upvotes: 2

gbehar
gbehar

Reputation: 1299

If I understand the question correctly, you know that you read some values AFTER another thread changed the value, but you don't see the change.

In fact it is not guaranteed that your reading thread will read the updated value of the writing thread without some synchronisation mechanism (you can read more here).

A solution that would work is to use atomic variables, for instance if you have an array of ints, change it to an array of atomic

std::atomic<int> arr[4];

Upvotes: 1

Related Questions