FREERTOS学习笔记,资源管理二

本文介绍了FreeRTOS中互斥体与任务调度的关系,特别是当任务优先级相同时,如何通过调用taskYIELD()避免资源竞争问题。此外,还详细讲解了看门人任务的概念,它作为资源管理的中介,通过队列管理其他任务的数据输出,避免优先级反转,并给出了vPrintString()的看门人任务实现示例。
摘要由CSDN通过智能技术生成

互斥体与任务调度

当两个需要使用同一个共享资源的任务优先级不同时,高优先级会在低优先级任务刚释放互斥体时打断低优先级任务。但当两个任务优先级相同时,任务二不会在任务一刚释放互斥体时马上抢占,而会等待任务一时间片执行完后再执行,此时会产生如下一种情况,
在这里插入图片描述
即当任务二释放互斥体后的时间片执行完前又开始了第二次循环,从而再次获取互斥体,此时会导致切换到任务一后,任务一无法得到互斥体而再次进入阻塞,从而任务二继续执行。
为了解决这个问题应采用调用taskYIELD() 接口的方法,即在释放互斥体后直接调度任务调度器。
例程如下:

void vFunction( void *pvParameter )
{
   
	extern SemaphoreHandle_t xMutex;
	char cTextBuffer[ 128 ];
	TickType_t xTimeAtWhichMutexWasTaken;
	for( ;; )
	{
   
		/* Generate the text string – this is a fast operation. */
		vGenerateTextInALocalBuffer( cTextBuffer );
		/* Obtain the mutex that is protecting access to the display. */
		xSemaphoreTake( xMutex, portMAX_DELAY );
		/* Record the time at which the mutex was taken. */
		xTimeAtWhichMutexWasTaken = xTaskGetTickCount();
		/* Write the generated text to the display – this is a slow operation. */
		vCopyTextToFrameBuffer( cTextBuffer );
		/* The text has been written to the display, so return the mutex. */
		xSemaphoreGive( xMutex );
		/* If taskYIELD() was called on each iteration then this task would only ever
		remain in the Running state for a short period of time, and processing time
		would be wasted by rapidly switching between tasks. Therefore, only call
		taskYIELD() if the tick count changed while the mutex was held. */
		if( xTaskGetTickCount() != xTimeAtWhichMutexWasTaken )
		{
   
			taskYIELD(
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值