- 消息队列的简介
消息队列是任务间通讯的机制,用于收发不定长消息的场合。
#include <oneos_config.h>
#include <dlog.h>
#include <os_errno.h>
#include <os_task.h>
#include <shell.h>
#include <string.h>
#include <os_memory.h>
#include <os_mq.h>
#define TEST_TAG "TEST"
#define TASK_STACK_SIZE 1024
#define TASK1_PRIORITY 15
#define TASK2_PRIORITY 16
#define MQ_MAX_MSG 10
#define TEST_NAME_MAX 16
#define STUDENT_NUM 5
static os_msgqueue_id mq_dynamic;
struct student_score
{
char name[TEST_NAME_MAX];
uint32_t score;
};
void task1_entry(void *para)
{
uint32_t i = 0;
struct student_score student_data;
char *name[STUDENT_NUM] = {"xiaoming", "xiaohua", "xiaoqiang", "xiaoli", "xiaofang"};
uint32_t score[STUDENT_NUM] = {80, 85, 90, 95, 96};
for (i = 0; i < STUDENT_NUM; i++)
{
memset(student_data.name, 0, TEST_NAME_MAX);
strncpy(student_data.name, name[i], TEST_NAME_MAX);
student_data.score = score[i];
if (OS_SUCCESS == os_msgqueue_send(mq_dynamic, &student_data, sizeof(struct student_score), OS_WAIT_FOREVER))
{
LOG_W(TEST_TAG, "task1 send -- name:%s score:%d", student_data.name, student_data.score);
}
os_task_msleep(100);
}
}
void task2_entry(void *para)
{
struct student_score student_data;
os_size_t recv_size = 0;
while (1)
{
if (OS_SUCCESS ==
os_msgqueue_recv(mq_dynamic, &student_data, sizeof(struct student_score), OS_WAIT_FOREVER, &recv_size))
{
LOG_W(TEST_TAG, "task2 recv -- name:%s score:%d", student_data.name, student_data.score);
}
}
}
void msgqueue_dynamic_sample(void)
{
os_task_id task1;
os_task_id task2;
mq_dynamic = os_msgqueue_create_dynamic("mq_dynamic", sizeof(struct student_score), MQ_MAX_MSG);
if (!mq_dynamic)
{
LOG_W(TEST_TAG, "msgqueue_dynamic_sample msgqueue create ERR");
}
task1 = os_task_create(OS_NULL, OS_NULL, TASK_STACK_SIZE, "task1", task1_entry, OS_NULL, TASK1_PRIORITY);
if (task1)
{
LOG_W(TEST_TAG, "msgqueue_dynamic_sample startup task1");
os_task_startup(task1);
}
os_task_msleep(200);
task2 = os_task_create(OS_NULL, OS_NULL, TASK_STACK_SIZE, "task2", task2_entry, OS_NULL, TASK2_PRIORITY);
if (task2)
{
LOG_W(TEST_TAG, "msgqueue_dynamic_sample startup task2");
os_task_startup(task2);
}
}
SH_CMD_EXPORT(dynamic_msgqueue, msgqueue_dynamic_sample, "test dynamic msgqueue");