互斥信号量
当一个任务想对临界区访问时,为了防止别的任务也对该临界区操作,它需要对该临界区上锁,即take(获取)一个互斥的信号量,以保证独享。
验证代码:
#include "mbed.h"
#include "rtos.h"
DigitalOut led1(PTB7);
DigitalOut led2(PTB6);
DigitalOut led3(PTB5);
Mutex stdio_mutex;
void notify(const char* name, int state)
{
stdio_mutex.lock();
if((const char*)name == "LED1")
{
led1 = state;
}
if((const char*)name == "LED2")
{
led2 = state;
}
if((const char*)name == "LED3")
{
led3 = state;
}
wait(0.5);
stdio_mutex.unlock();
}
void test_thread(void const *args)
{
while (true)
{
notify((const char*)args, 0);
Thread::wait(1000);
notify((const char*)args, 1);
Thread::wait(1000);
}
}
int main()
{
Thread t2(test_thread, (void *)"LED2");
Thread t3(test_thread, (void *)"LED3");
test_thread((void *)"LED1");
}
运行效果:
|