[英]How to implement the __sync_fetch_and_sub atomic operation in assembly language based on Linux GCC
我需要使用基於GCC 3.4的匯編語言編寫自己的__sync_fetch_and_sub
原子操作的實現, __sync_fetch_and_sub
語言沒有內置__sync_fetch_and_sub
。 但是我對組裝一無所知。
誰能幫我? 任何幫助將不勝感激!!
這是__sync_fetch_and_add
的實現
inline unsigned int __sync_fetch_and_add(volatile unsigned int* p, unsigned int incr)
{
unsigned int result;
__asm__ _volatile_ ("lock; xadd %0, %1" :
"=r"(result), "=m"(*p):
"0"(incr), "m"(*p) :
"memory");
return result;
}
__sync_fetch_and_add(int *ptr, int a_count)
是將a_count自動添加到ptr指向的變量中。 返回以前在內存中的值。
__sync_fetch_and_sub(int *ptr, int a_count)
是從ptr指向的變量中自動減去a_count。 返回以前在內存中的值。
此代碼段使用xadd
的原子版本:exchange和add:將原子的右邊操作數原子地添加到左邊(這里是內存),並在右邊的操作數中返回內存中的初始值。 之前的lock
語句可確保操作的原子性。
但是,gcc使用AT&T表示法,因此該解釋中的左右參數(取自intel手冊)是相反的。
由於intel體系結構上沒有xsub
指令,因此最簡單的模擬方法是首先取與要減去的數字相反的值,然后原子地對其進行添加/交換:
inline unsigned int __sync_fetch_and_sub(volatile unsigned int* p,
unsigned int decr)
{
unsigned int result;
__asm__ __volatile__ ("lock; xadd %0, %1"
:"=r"(result), "=m"(*p)
:"0"(-decr), "m"(*p)
:"memory");
return result;
}
我還刪除了
unsigned
屬性,在這種情況下我發現它們不相關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.