Primitive concurrent read and write thread safety

  • A simplified illustration below, how does .NET deal with this?
  • and if this causes problems, will I have to block / block access to each field / property, which can be written to + access from different streams from time to time?

Field somewhere

public class CrossRoads(){
    public int _timeouts;
}

Background Stream Creator

public void TimeIsUp(CrossRoads crossRoads){
    crossRoads._timeouts++;
}

Perhaps at the same time, trying to read elsewhere

public void HowManyTimeOuts(CrossRoads crossRoads){
    int timeOuts = crossRoads._timeouts;
}
+5
source share
5 answers

The simple answer is that the code above can cause problems when accessing multiple threads at the same time.

The .Net framework provides two solutions: blocking and thread synchronization.

(.. ints) .

, (Increment and Decrement), :

IncrementCount CrossRoads:

public void IncrementCount() {
    Interlocked.Increment(ref _timeouts);
}

:

public void TimeIsUp(CrossRoads crossRoads){
    crossRoads.IncrementCount();
}

, 64- 32- , . . Interlocked.Read method.

( # SyncLock VB.Net).

, (, ), () :

    private static object SynchronizationObject = new Object();

    public void PerformSomeCriticalWork()
    {
        lock (SynchronizationObject)
        {
            // do some critical work
        }
    }
+11

, ints , . , ++, . .

:

Interlocked.Increment(ref crossroads._timeouts);

, , , ;

int timeouts = Interlocked.CompareExchange(ref crossroads._timeouts, 0, 0);

, , . , "", , , , Interlocked (IMO) . , .

+4

, #, :

.NET ?

. , .

/ /, + ?

. , , . , .

+3

dotnet. crossRoads._timeouts++ INC [memory]. Read-Modify-Write. * ( , ), .

:

, TimeIsUp() - crossRoads._timeouts, , TimeIsUp(), . TimeIsUp() , HowManyTimeOuts() ( ) . crossRoads._timeouts , - , .

, .

(*) , , x86 , , ​​, . , REP.

+3

, int "" ( 32 64 ), , .

, / int.

You can also use it Interlocked.Incrementfor your purposes here.

+2
source

All Articles