gpt4 book ai didi

Cortex M3 - 如何使用信号量

转载 作者:太空狗 更新时间:2023-10-29 15:36:39 24 4
gpt4 key购买 nike

我有一个关于在 cortex m3 中使用信号量的问题。我发现了一个线程“ARM cortex:mutex using bit banding”ARM cortex: mutex using bit banding .有一个简短的问题描述,最后一个答案对我的问题有好处 - 但我不确定如何在 c/c++ 中实现它。

“我从未在 ARM 上使用过位带;我倾向于对所有此类操作使用加载独占/存储条件。使用循环加载独占旧值,计算新值,并使用条件存储将其写回。循环直到条件存储成功(如果不是第一次,它可能会第二次成功)。”

如果有人可以发布一个简短的代码如何使用它,我将不胜感激。

谢谢,马丁

最佳答案

请注意,位带并非在所有实现中都可用(最值得注意的是,它在 NXP 的 LPC1xxx 系列中缺失)。

有关使用 LDREX/STREX 实现信号量的官方方法,请参阅 ARM Synchronization Primitives Development Article .它使用 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;
}
};

关于Cortex M3 - 如何使用信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8893206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com