在多线程环境中,对共享的变量的访问,可以使用基于Compare And Swap这种lock free的技术进行实现,这种实现的好处是效率高。

一、原子操作摘录

1.1 Android

  源码:system/core/libcutils /atomic.c(针对X86):

 1 #elif defined(__i386__) || defined(__x86_64__)
 2 
 3 void android_atomic_write(int32_t value, volatile int32_t* addr) {
 4     int32_t oldValue;
 5     do {
 6         oldValue = *addr;
 7     } while (android_atomic_cmpxchg(oldValue, value, addr));
 8 }
 9 
10 int32_t android_atomic_inc(volatile int32_t* addr) {
11     int32_t oldValue;
12     do {
13         oldValue = *addr;
14     } while (android_atomic_cmpxchg(oldValue, oldValue+1, addr));
15     return oldValue;
16 }
17 
18 int32_t android_atomic_dec(volatile int32_t* addr) {
19     int32_t oldValue;
20     do {
21         oldValue = *addr;
22     } while (android_atomic_cmpxchg(oldValue, oldValue-1, addr));
23     return oldValue;
24 }
25 
26 int32_t android_atomic_add(int32_t value, volatile int32_t* addr){
27     int32_t oldValue;
28     do {
29         oldValue = *addr;
30     } while (android_atomic_cmpxchg(oldValue, oldValue+value, addr));
31     return oldValue;
32 }
33 
34 int android_atomic_cmpxchg(int32_t oldvalue, int32_t newvalue, volatile int32_t* addr) {
35     int xchg;
36     asm volatile
37     (
38         " lock; cmpxchg %%ecx, (%%edx);"
39         " setne %%al;"
40         " andl $1, %%eax"
41         : "=a" (xchg)
42         : "a" (oldvalue), "c" (newvalue), "d" (addr)
43     );
44     return xchg;
45 }
View Code

相关文章: