[文章]【OpenHarmony成长计划挑战赛】基于Openarmony的碳侦测无人机:Mutex

阅读量0
0
1

2、内核编程开发——mutex

Niobe WiFi IoT开发板上使用cmsis 2.0 接口进行互斥锁开发mutex.png

mutex API分析

osThreadNew()

osThreadId_t osThreadNew(osThreadFunc_tfunc, void *argument,const osThreadAttr_t *attr )

描述:

线程函数

参数:

名字 描述
func 线程函数.
argument 启动参数传递指针
attr 线程属性

osMutexNew()

osMutexNew (const osMutexAttr_t *attr);

描述:

创建互斥锁

参数:

名字 描述
attr mutex属性

osMutexAcquire()

osMutexAcquire (osMutexId_t mutex_id, uint32_t timeout);

描述:

获取互斥锁

参数:

名字 描述
mutex_id mutex ID
timeout delay时间

osMutexRelease()

osMutexRelease (osMutexId_t mutex_id);

描述:

释放互斥锁

参数:

名字 描述
mutex_id mutex ID

软件设计

主要代码分析

在os_mutex_example函数中,通过osThreadNew()函数创建了firstThread、twoThread、threeThread三个线程,firstThread、twoThread、threeThread三个线程启动后会输出打印日志。

void firstThread(void)
{
osDelay(100U);
while(1)
{
osMutexAcquire(mutex_id, osWaitForever);
    printf("firstThread is Acquire.\r\n");
    osDelay(100U);
osMutexRelease(mutex_id);
}
}
​
void twoThread(void)
{
osDelay(100U);
while(1) 
{
printf("twoThread is Acquire.\r\n");
    osDelay(100U);
}
}
​
void threeThread(void)
{
    while(1)
{
osMutexAcquire(mutex_id, osWaitForever);
printf("threeThread is Acquire.\r\n");
osDelay(300U);
osMutexRelease(mutex_id);
}
}
​
void os_mutex_example(void)
{
    osThreadAttr_t attr;
​
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
​
    attr.name = "firstThread";
    attr.priority = 26;
    if (osThreadNew((osThreadFunc_t)firstThread, NULL, &attr) == NULL)
{
    printf("create firstThread failed!\n");
    }
​
attr.name = "twoThread";
    attr.priority = 25;
    if (osThreadNew((osThreadFunc_t)twoThread, NULL, &attr) == NULL)
    {
      printf("create twoThread failed!\n");
    }
​
    attr.name = "threeThread";
    attr.priority = 24;
    if (osThreadNew((osThreadFunc_t)threeThread, NULL, &attr) == NULL)
    {
      printf("create threeThread failed!\n");
    }
​
mutex_id = osMutexNew(NULL);
    if (mutex_id == NULL)
    {
      printf("create Mutex failed!\n");
    }
}

编译调试

修改 BUILD.gn 文件

**修改 **applications/app路径下 BUILD.gn 文件,指定 mutex_example 参与编译。

#"TW001_OS_helloworld:helloworld_example",
"TW005_OS_mutex:mutex_example",
#"TW003_OS_timer:os_timer_example",
#"TW004_OS_event:os_event_example",
#"TW005_OS_mutex:os_mutex_example",
#"TW006_OS_semp:os_semaphore_example",
#"TW007_OS_message:os_message_example",

运行结果

示例代码编译烧录代码后,按下开发板的RESET按键,通过串口助手查看日志,显示如下

firstThread is Acquire
twoThread is Acquire
threeThread is Acquire

回帖

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容图片侵权或者其他问题,请联系本站作侵删。 侵权投诉
链接复制成功,分享给好友