Array of objects, updating in one thread and reading in another

Simplified question to give a clearer idea of ​​what I am actually asking

I have two threads, name them Aand B. They divide one type object Foothat has a field under the name Nameand is stored in the type array Foo[]by index 0. Streams will always have access to the index 0in the order that is already guaranteed by the system, so there is no race condition for the stream Bpreceding the stream A.

This is the order.

 // Thread A
 array[0].Name = "Jason";

 // Thread B
 string theName = array[0].Name

As I said, this order is already guaranteed, there is no way for stream B to read the value before stream A

I want to provide two things:

  • Both threads get the last object with index 0.
  • B .Name

Name, volatile , , volatile.

, 1, ( ), .VolatileRead:

 // Thread A
 Foo obj = (Foo)Thread.VolatileRead(ref array[0]);
 obj.Name = "Jason";

 // Thread B
 Foo obj = (Foo)Thread.VolatileRead(ref array[0]);
 string theName = obj.Name

:

 // Thread A
 array[0].Name = "Jason";
 Thread.MemoryBarrier();

 // Thread B
 Thread.MemoryBarrier();
 string theName = array[0].Name

, : , 2? , ? 0 , Name. VolatileRead MemoryBarrier 0 , IN 0 ?

+5
2

lock volatile . :

  • volatile , , , , (.. ), . , .
  • lock , / , . , , .

, :

Thread A read Name
Thread A modify Name
Thread B read Name

, (, AutoresetEvent):

//Thread A
foo[0].Name = "John"; // write value
event.Set(); // signal B that write is completed

//Thread B
event.WaitOne(); // wait for signal
string name = foo[0].Name; // read value

, B Name , A .

: , , . , volatile, Thread.MemoryBarrier() , :

//Thread A
foo[0].Name = "John"; // write value
Thread.MemoryBarrier();

//Thread B
Thread.MemoryBarrier();
string name = foo[0].Name; // read value

: http://www.albahari.com/threading/part4.aspx

+2

, . , () .

Thread.MemoryBarrier. . x86, , PPC, .

0

All Articles