淄博專業(yè)做網(wǎng)站簡(jiǎn)單免費(fèi)制作手機(jī)網(wǎng)站
自旋鎖作用
? ? ? 自旋鎖的是為了保護(hù)兩個(gè)核上的公共資源,也就是全局變量,只有在一方也就是一個(gè)核搶到了自選鎖,才能對(duì)公共資源進(jìn)行操作修改,當(dāng)然還有其他形似的鎖如互斥鎖,這里不比較兩者的區(qū)別,以前沒有深入的去了解自旋鎖的底層實(shí)現(xiàn),只是簡(jiǎn)單調(diào)用。
自旋鎖原理
? ? ?自旋鎖的底層實(shí)現(xiàn)原理其實(shí)是用到了各個(gè)架構(gòu)比較交換的匯編指令,英飛凌的TriCore架構(gòu)為
CMPSWAP.W,ARM架構(gòu)雖然沒有比較交換指令,但是通過關(guān)閉preempt_disable禁止搶占來實(shí)現(xiàn)原子操作。
數(shù)據(jù)總線
? ? ??數(shù)據(jù)總線的一些基本概念這里就不提出來再講了。有一個(gè)細(xì)節(jié)是在總線上同一時(shí)刻只能有一個(gè)主設(shè)備控制總線傳輸操作。而對(duì)于多核來說也是如此,他們需要互相爭(zhēng)搶總線的使用權(quán),而這一現(xiàn)象又能幫助我們實(shí)現(xiàn)一些原子操作。
總線操作
? ??使用總線對(duì)數(shù)據(jù)進(jìn)行操作的時(shí)候并不是全部都能一次完成的,有時(shí)候可能需要多個(gè)操作才能實(shí)現(xiàn)我們編程中看似簡(jiǎn)單的操作,而在找個(gè)時(shí)候就不一定能滿足我們的原子性了。
TriCore架構(gòu)自旋鎖實(shí)現(xiàn)
boolean IfxCpu_acquireMutex(IfxCpu_mutexLock *lock)
{boolean retVal;volatile uint32 spinLockVal;retVal = FALSE;spinLockVal = 1UL;spinLockVal =(uint32)__cmpAndSwap(((unsigned int *)lock), spinLockVal, 0);/* Check if the SpinLock WAS set before the attempt to acquire spinlock */if (spinLockVal == 0){retVal = TRUE;}return retVal;
}/** \brief This function is a implementation of a binary semaphore using compare and swap instruction* \param address address of resource.* \param value This variable is updated with status of address* \param condition if the value of address matches with the value of condition, then swap of value & address occurs.**/
IFX_INLINE unsigned int Ifx__cmpAndSwap (unsigned int volatile *address,unsigned int value, unsigned int condition)
{unsigned long long reg64= value | (unsigned long long) condition << 32;__asm__ __volatile__ ("cmpswap.w [%[addr]]0, %A[reg]": [reg] "+d" (reg64): [addr] "a" (address): "memory");return reg64;
}
? ?這段代碼的邏輯及其簡(jiǎn)單,就是去查找我們lock變量的值是否為0,如果為0便把它賦值為1,并且返回成功搶到鎖的信息。而有一個(gè)操作是值得關(guān)注的。__cmpAndSwap()?這一操作為什么能保證原子性并且能做到對(duì)變量進(jìn)行加鎖的呢?這里使用了匯編語(yǔ)言對(duì)芯片進(jìn)行操作,而cmpswap.w操作正是我們?cè)跀?shù)據(jù)手冊(cè)中找到的新指令。而正如注釋說這一個(gè)指令能比較兩個(gè)地址中的值是否相同,并完成交換。
? ?cmpswap.w等效如下代碼:
tmp = *x; //#tmp address的值
if(*x == z) // # z為condition
{*x = y; //#*address = values;
}
else
{*x = tmp;
}
return tmp
PowerPC架構(gòu)自旋鎖實(shí)現(xiàn)?
static inline uint32 aSpinlock_Hal_Swap(uint32 Addr, register uint32 Value)
{uint32 result;register uint32 temp1,temp2;__asm__ __volatile__(/* prepare the decoration for the SWAP instruction */"mr %[temp11], %[Value]" "\n" /* load value in r6 */"e_lis %[temp22], 0x5000" "\n" /* r5 = 0x50000000 */"se_or %[temp11], %[temp22]" "\n" /* Value = Value | r5 *//* lwdcbx -> Load Word Decorated with Cache Bypass */"lwdcbx %[result], %[temp11], %[Addr]" "\n" /* SWAP Addr with r3 */: [result] "=r" (result): [Addr] "b" (Addr), [temp11]"r" (temp1), [temp22]"r" (temp2) , [Value]"r" (Value): "cc");return result;
}
? ? ?參考文檔:
??Aurix/Tricore實(shí)驗(yàn)分享之103: 硬件mutex指令|英飛凌開發(fā)者技術(shù)社區(qū)
??TriCore架構(gòu)多核多線程鎖探究(TC264雙核互斥鎖)-CSDN博客
? ?https://www.cnblogs.com/DoOrDie/p/9265754.html