[英]Cortex M3 - how to use semaphores
我有一個關於在皮質m3中使用信號量的問題。 我找到了一個帖子“ARM cortex:mutex using bit banding” ARM cortex:mutex using bit banding 。 有一個簡短的問題描述,最后的答案對我的問題有好處 - 但我不知道如何在c / c ++中實現它。
“我從來沒有在ARM上使用過bit-banding;我傾向於對所有這些操作使用load-exclusive / store-conditional。使用循環來加載舊值,計算新值,然后使用寫回來的條件存儲。循環直到條件存儲成功(它可能是第二次,如果它不是第一次)。“
如果有人可以發布一個簡短的代碼如何使用它,我將非常感激。
謝謝,馬丁
請注意,並非所有實現都可以使用位帶(最值得注意的是,它在恩智浦的LPC1xxx系列中缺失)。
有關使用LDREX / STREX實現信號量的官方方法,請參閱ARM同步原語開發文章 。 它使用ARM程序集。
下面是我制作的一個簡單的類,它使用編譯器內在函數(未經測試!)。 該名稱可能用詞不當,因為它實際上像互斥鎖一樣工作。 它也缺少可能需要的DMB指令。
class Semaphore
{
enum { SemFree, SemTaken };
// semaphore value
int s;
public:
// constructor
Semaphore(): s(SemFree) {};
// try to take the semaphore and return success
// by default block until succeeded
bool take(bool block = true)
{
int oldval;
#if defined(TARGET_LPC1768) // on Cortex-M3 we can use ldrex/strex
do {
// read the semaphore value
oldval = __ldrex(&s);
// loop again if it is locked and we are blocking
// or setting it with strex failed
}
while ( (block && oldval == SemTaken) || __strex(SemTaken, &s) != 0 );
if ( !block ) __clrex(); // clear exclusive lock set by ldrex
#else // on arm7 there's only swp
do {
// swp sets the pointed data to the given value and returns the previous one
oldval = __swp(SemTaken, &s);
// if blocking, loop until the previous value becomes 0
// which would mean we have successfully taken the lock
}
while (block && oldval == SemTaken);
#endif
return oldval == SemFree;
}
// release the semaphore
void release()
{
s = SemFree;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.