一、概念
二、没有使用互斥量的时候
配置中、高、低三个优先级
osThreadDef(TaskH, StartTaskH, osPriorityAboveNormal, 0, 128);
TaskHHandle = osThreadCreate(osThread(TaskH), NULL);
osThreadDef(TaskM, StartTaskM, osPriorityNormal, 0, 128);
TaskMHandle = osThreadCreate(osThread(TaskM), NULL);
osThreadDef(TaskL, StartTaskL, osPriorityBelowNormal, 0, 128);
TaskLHandle = osThreadCreate(osThread(TaskL), NULL);
void StartTaskH(void const * argument)
{
for(;;)
{
xSemaphoreTake(myBinarySemHandle,portMAX_DELAY);
printf("TaskH:我开始进入厕所,发功中。。\r\n");
HAL_Delay(1000);
printf("TaskH:我上完厕所了,真舒服。。。\r\n");
xSemaphoreGive(myBinarySemHandle);
osDelay(1000);
}
}
void StartTaskM(void const * argument)
{
for(;;)
{
printf("TaskM:我就是为了占用资源,带女朋友兜风\r\n");
osDelay(1000);
}
}
void StartTaskL(void const * argument)
{
for(;;)
{
xSemaphoreTake(myBinarySemHandle,portMAX_DELAY);
printf("TaskL:我开始进入厕所,发功中。。\r\n");
HAL_Delay(3000);
printf("TaskL:我上完厕所了,真舒服。。。\r\n");
xSemaphoreGive(myBinarySemHandle);
osDelay(1000);
}
}
首先删除二值信号量
创建互斥量
void MX_FREERTOS_Init(void) {
osMutexDef(myMutex);
myMutexHandle = osMutexCreate(osMutex(myMutex));
osThreadDef(TaskH, StartTaskH, osPriorityAboveNormal, 0, 128);
TaskHHandle = osThreadCreate(osThread(TaskH), NULL);
osThreadDef(TaskM, StartTaskM, osPriorityNormal, 0, 128);
TaskMHandle = osThreadCreate(osThread(TaskM), NULL);
osThreadDef(TaskL, StartTaskL, osPriorityBelowNormal, 0, 128);
TaskLHandle = osThreadCreate(osThread(TaskL), NULL);
}
void StartTaskH(void const * argument)
{
for(;;)
{
xSemaphoreTake(myMutexHandle,portMAX_DELAY);//句柄变为myMutexHandle
printf("TaskH:我开始进入厕所,发功中。。\r\n");
HAL_Delay(1000);
printf("TaskH:我上完厕所了,真舒服。。。\r\n");
xSemaphoreGive(myMutexHandle);
osDelay(1000);
}
}
void StartTaskM(void const * argument)
{
for(;;)
{
printf("TaskM:我就是为了占用资源,带女朋友兜风\r\n");
osDelay(1000);
}
}
void StartTaskL(void const * argument)
{
for(;;)
{
xSemaphoreTake(myMutexHandle,portMAX_DELAY);
printf("TaskL:我开始进入厕所,发功中。。\r\n");
HAL_Delay(3000);
printf("TaskL:我上完厕所了,真舒服。。。\r\n");
xSemaphoreGive(myMutexHandle);
osDelay(1000);
}
}
运行结果:
通过引入互斥量,可以实现资源的保护功能。