android的原子操作(x86)

來源:互聯網
上載者:User

 

  • cmpxchg 在 android 的作用是完成原子級的操作,比如自加,自減等。
  • cmpxchg 存在於 486 及更進階 CPU,其它類型的 CPU 如 Arm 則沒有這條指令。

cmpxchg 指令被封裝於函數 android_atomic_cmpxchg ,該函數位於 atomic.c ,並被預先處理語句

#elif defined(__i386__) || defined(__x86_64__)

所保護。

1 源碼分析:


 

注釋的引用連結是:

  • gnu asm template syntax
  • lock
  • cmpxchg instruction
  • setne

因此該函數的作用就是: 如果 oldvalue == *addr, 則將 newvalue 的值賦 給 *addr, 然後返回 1, 否則返回 0

(返回1表示已經將新值賦給了變數/寄存器, 0則表示沒有賦值)

2 例子: 2.1 oldval == newval
int32_t a = 5;int b = android_atomic_cmpxchg( a, a+1, &a );printf("%d, %d\n", a, b);

結果是:

6, 1
2.2 oldval != newval
int32_t a = 5;int b= android_atomic_cmpxchg( a, a, &a );printf("%d, %d\n", a, b);

結果是:

5, 0
3 引用

其它函數如 android_atomic_inc, android_atomic_dec 等都使用了 android_atomic_cmpxchg 實現,這些函數統一放在 atomic.c

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.