原子访问

线程同步一大部分与原子访问(atomic access)有关, 所谓原子访问, 指的是一个线程在访问某个资源的同时能够保证没有其他线程会在同一时刻访问同一资源.

假设编译器将g_x递增的那行代码时,生成了下面的汇编代码:
MOV EAX, [g_x] ;   Move the value in g_x into a register
INC EAX        ;   Increment the value in the register
MOV [g_x] , EAX;   Store the new value back in g_x
 
两个线程不太可能在完全相同的时刻执行上面的代码. 但如果是下面这样呢?
MOV EAX, [g_x]  ;  thread1: move 0 into a register
INC EAX         ;  thread1: Increment the register to 1
 
MOV EAX, [g_x]  ;  thread2: Move 0 into a register
INC EAX         ;  thread2: Increment the register to 1
MOV [g_x], EAX  ;  thread2: Store 1 back in g_x
 
MOV [g_x] , EAX ; thread 1 : Store 1 back in g_x.
 
结果显而易见,这是不正确的,多个线程访问同一资源的方式.
为了解决这个问题,需要一种方法能够保证对一个值的递增操作是原子操作---就是说,不会被打断,Interlocked系列函数为我们提供了这种解决方案,所有这些函数会以原子方式操作一个值.
 
原文地址:https://www.cnblogs.com/xiejiulong/p/3924739.html