Mutex
Mutex 类层次结构
Mutex 用于同步线程的执行,例如,以保护对共享资源的访问。
注意: 无法从中断服务例程(ISR)调用 Mutex 方法。在当前版本的 Mbed OS 中,如果您尝试在 ISR 中使用互斥锁,则不会发生任何事情;无论锁实际上是否空闲,尝试锁定互斥锁都会立即成功。换句话说,如果在 ISR 中获得互斥锁,则可以破坏线程安全机制并将竞争条件引入其他安全的代码段。未来版本的 Mbed OS 将提供警告并最终防止这种情况发生。
注意: 对于所有驱动程序,Mbed OS 使用 PlatformMutex 类而不是 RTOS 互斥锁。
Mutex 类参考
公共成员函数 | |
Mutex () | |
Mutex (const char *name) | |
osStatus | lock (uint32_t millisec=osWaitForever) |
bool | trylock () |
bool | trylock_for (uint32_t millisec) |
bool | trylock_until (uint64_t millisec) |
osStatus | unlock () |
osThreadId | get_owner () |
~Mutex () |
友元 | |
class | ConditionVariable |
Mutex 示例
使用 Mutex 保护 printf()。
#include "mbed.h"
Mutex stdio_mutex;
Thread t2;
Thread t3;
void notify(const char* name, int state) {
stdio_mutex.lock();
printf("%s: %d\n\r", name, state);
stdio_mutex.unlock();
}
void test_thread(void const *args) {
while (true) {
notify((const char*)args, 0); wait(1);
notify((const char*)args, 1); wait(1);
}
}
int main() {
t2.start(callback(test_thread, (void *)"Th 2"));
t3.start(callback(test_thread, (void *)"Th 3"));
test_thread((void *)"Th 1");
}
注意: C 标准库互斥体
Arm C 标准库已经具有互斥锁以保护对 stdio 的访问,因此在 LPC1768 上不需要上述示例。另一方面,LPC11U24 不提供默认的 stdio Mutexes,因此上述示例是必需的。
注意: 由于 Arm C 标准库中的互斥锁,您不能在 ISR 中使用 stdio(printf,putc,getc 等),malloc 和 new。
相关内容
- PlatformMutex API 参考。