FreeRTOS中两个同等级无阻塞打印任务,只有一个能正常打印

环境:STM32CubeMX+MDK5

printf重定向用的是官方例子

#ifdef __GNUC__
  /* With GCC, small printf (option LD Linker->Libraries->Small printf
     set to 'Yes') calls __io_putchar() */
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF); 

  return ch;
}

运行FreeRTOS实时内核使用指南中两个相同优先级的无阻塞打印任务出现如图情况

尝试Debug过,一步步执行发现,任务1也会被执行到,就是打印不出信息。

将printf重定向换成标准库的方式

#pragma import(__use_no_semihosting)             
//标准库需要的支持函数                 
struct __FILE 
{ 
    int handle; 
}; 

FILE __stdout;       
//定义_sys_exit()以避免使用半主机模式    
void _sys_exit(int x) 
{ 
    x = x; 
} 
//重定义fputc函数 
int fputc(int ch, FILE *f)
{      
    while((USART1->SR&0X40)==0){};//循环发送,直到发送完毕  
    USART1->DR = (uint8_t) ch;
    return ch;
}

虽然打印是乱了,好歹打印出来了是不是。

再改进一下,在调用printf的时候加个锁。

#define PRINTF(format,...) \
	osMutexWait(task_mutexHandle, 1000U); \
	printf(format,__VA_ARGS__); \
	osMutexRelease(task_mutexHandle);

完美解决~打完收工

 


版权声明:本文为JasonTD原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。