官方文档参考
107 Access by Multiple Tasks
[[FreeRTOS_Mastering_the_FreeRTOS_Real_Time_Kernel-A_Hands-On_Tutorial_Guide.pdf#page=133&selection=0,3,2,24|FreeRTOS_Mastering_the_FreeRTOS_Real_Time_Kernel-A_Hands-On_Tutorial_Guide, page 133]]
消息队列的多进单出
多个任务共享一个消息队列进行读写操作。
使用时,对不不同任务的优先级设置十分重要。
示例代码
#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_chip_info.h"
#include "esp_flash.h"
#include "esp_system.h"
#include "freertos/queue.h"
void sender_task_1(void *pvPara)
{
QueueHandle_t QHandle = (QueueHandle_t)pvPara;
int numToSend = 1;
while (true) {
xQueueSendToBack(QHandle, &numToSend, 0);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void sender_task_2(void *pvPara)
{
QueueHandle_t QHandle = (QueueHandle_t)pvPara;
int numToSend = 2;
while (true) {
xQueueSendToBack(QHandle, &numToSend, 0);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void receiver_task(void *pvPara)
{
QueueHandle_t QHandle = (QueueHandle_t)pvPara;
int numToReceive = 0;
while (true) {
xQueueReceive(QHandle, &numToReceive, portMAX_DELAY);
printf("[RECEIVER]: %d\n", numToReceive);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
void app_main(void)
{
QueueHandle_t QHandle = xQueueCreate(5, sizeof(int));
if (QHandle) {
xTaskCreate(sender_task_1, "Sender Task 1", 2048, (void *)QHandle, 2, NULL);
xTaskCreate(sender_task_2, "Sender Task 2", 2048, (void *)QHandle, 1, NULL);
xTaskCreate(receiver_task, "Receiver Task", 2048, (void *)QHandle, 3, NULL);
} else {
printf("[MAIN]: Do not have enough memory to create a queue.\n");
}
}
代码中可以看到任务设置了不同的优先级:
- Sender Task 1 的优先级是 2
- Sender Task 2 的优先级是1
- 而接收任务的优先级是 3,高于发送任务
此代码运行于单核和多核 CPU 是有区别的,单核会看出明显的优先级区别;而多核,仍然会看到
1
和2
交替输出。