Today I accidentally stumbled upon a MemoryBarrier and realized that I do not fully understand the work of the CPU with RAM. The search did not give me an unambiguous answer to the question, so I decided to ask a new question.
There are two arrays:
int[] dataStates; //default items value is 0
MyStruct[] data; //MyStruct is a struct with several fields
There are two threads (ThreadA, ThreadB)
ThreadA performs the following code:
data[index] = ... //new value
//change to "1" after setting data
Interlocked.Exchange(ref dataStates[index], 1);
ThreadB code:
//wait for "1" in array item and replace to "2"
while(Interlocked.CompareExchange(ref dataStates[index], 2, 1) != 1)
{
Thread.Sleep(0);
}
//read actual data
var value = data[index];
Is it possible that the Thread will read the data from the data[index] and they will be obsolete? By the word obsolete, I mean that the data received from the array will not match the data that was set before the Interlocked.Exchange call.
In general, I try data transfer between threads in the most productive way. Do use this approach (without locks) is it appropriate or are there more acceptable approaches?