基于STM32互斥量具体实例: // 定义共享资源变量
rt_uint16_t mutex_num1 = 0;
rt_uint16_t mutex_num2 = 0;
// 定义互斥量控制块
static rt_mutex_t mutex_num = RT_NULL;
//创建互斥量
mutex_num = rt_mutex_create("mutex_test",RT_IPC_FLAG_FIFO);
if(mutex_num != RT_NULL)
{
rt_kprintf("mutex create sucessful\n");
}
else
{
rt_kprintf("mutex create fial\n");
return -1;
}
//创建线程
led1_thread = rt_thread_create("led1",task1,RT_NULL,1024,2,10);
if(led1_thread != RT_NULL)
rt_thread_startup(led1_thread);
else
return -1;
led2_thread = rt_thread_create("led2",task2,RT_NULL,1024,3,5);
if(led2_thread != RT_NULL)
rt_thread_startup(led2_thread);
else
return -1;
// 入口函数
oid task1(void *parameter)
{
while(1)
{
rt_mutex_take(mutex_num,RT_WAITING_FOREVER);
mutex_num1 ++;
rt_thread_mdelay(100);
mutex_num2 ++;
rt_mutex_release(mutex_num);
}
}
void task2(void *parameter)
{
while(1)
{
rt_mutex_take(mutex_num,RT_WAITING_FOREVER);
if(mutex_num1 != mutex_num2)
{
rt_kprintf("mutex is Fial\n");
}
else
{
rt_kprintf("mutex is sucessful\n");
}
rt_mutex_release(mutex_num);
rt_thread_mdelay(1000);
}
}
|