Lock only 1 operation?

ive asked himself: "why should I use locks for only one statement" ...

(IMHO - if his operation 1 is only as an appointment - then there should be no problem ..)?

then I saw this:

As a basic rule, you need to block access to any writable sharing field. Even in the simplest case - assignment operation on one field - you should consider synchronization. In the following class, neither the Increment method nor Assign are thread safe:

class ThreadUnsafe
{
  static int _x;
  static void Increment() { _x++; }  
  static void Assign() { _x = 123; }
}

Could you tell me why this is not thread safe? ive ran a lot of scripts in my head and couldn't find any problems ...

+5
source share
4 answers

, . _x = 0. , Increment Assign . , 100 ( ) 101 ( ).

(EDIT: , !)

 Thread 1 (executing Increment)    Thread 2 (executing Assign 100)
 -----------------------------------------------------------------
 read _x onto stack       (= 0)
                                   put 100 on top of stack
                                   write top of stack to _x (= 100)
 increment top of stack   (= 1)
 write top of stack to _x (= 1)

_x 1, 100, 101.

, , . , .


, :

 Thread 1 (executing Increment)    Thread 2 (executing Assign 100)
 -----------------------------------------------------------------
 lock (success)
 read _x onto stack       (= 0)
                                   lock (lock already taken; 
                                   |     wait until Thead 1 lock is released)
 increment top of stack   (= 1)    |
 write top of stack to _x (= 1)    |
 unlock                            |
                                   +> (success)
                                   put 100 on top of stack
                                   write top of stack to _x (= 100)
                                   unlock

100. , , .

+4

MSIL...

.method private hidebysig static void  Increment() cil managed
{
  // Code size       14 (0xe)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldsfld     int32 ThreadUnsafe::_x
  IL_0006:  ldc.i4.1
  IL_0007:  add
  IL_0008:  stsfld     int32 ThreadUnsafe::_x
  IL_000d:  ret
} // end of method ThreadUnsafe::Increment

, , MSIL . JIT , , - , , , , . , 2 X "load" "store" - , X + X X + 2 X = X.

, .

+4

, .

,

a) ( )

b) , ( )

, ( ) 32- , . , / 64- ? A 128? , , a, b, ( ) , .

.

+1

All Articles