欢迎关注VxWorks567
如转发 请标明出处!
分享一段代码,适合初学者
代码语言:javascript复制/*
* 公众号 VxWorks567
*/
#include <stdio.h>
#include <taskLib.h>
#include <msgQLib.h>
#define CONSUMER_TASK_PRI 102
#define PRODUCER_TASK_PRI 101
#define TASK_STACK_SIZE 5000
#define MSG_NUM 10
struct msg
{
int tid;
int value;
};
static void producerTask(MSG_Q_ID msgQId)
{
struct msg producedItem;
int count;
printf("n%s startedn", taskName(0));
for(count = 1; count <= MSG_NUM; count )
{
producedItem.tid = taskIdSelf();
producedItem.value = count * 10;
if((msgQSend(msgQId, (char *)&producedItem, sizeof(producedItem), WAIT_FOREVER, MSG_PRI_NORMAL)) == ERROR)
{
printf("Error in sending the message");
return;
}
else
printf("%s: produced msg %d n", taskName(0), producedItem.value);
}
return;
}
static void consumerTask(MSG_Q_ID msgQId)
{
struct msg consumedItem;
int count;
printf("n%s: Startedn", taskName(0));
for(count = 1; count <= MSG_NUM; count )
{
if((msgQReceive(msgQId, (char *) &consumedItem, sizeof(consumedItem), WAIT_FOREVER)) == ERROR)
{
printf("Error in receiving the message");
return;
}
else
printf("%s: Consuming msg %dn", taskName(0), consumedItem.value);
}
msgQDelete(msgQId);
return;
}
void testTaskMsgQ()
{
MSG_Q_ID msgQId = msgQCreate(MSG_NUM, sizeof(struct msg), MSG_Q_FIFO);
taskSpawn("tProducerTask", PRODUCER_TASK_PRI, 0, TASK_STACK_SIZE, (FUNCPTR)producerTask, (int)msgQId, 0, 0, 0, 0, 0, 0, 0, 0, 0);
taskSpawn("tConsumerTask", CONSUMER_TASK_PRI, 0, TASK_STACK_SIZE, (FUNCPTR)consumerTask, (int)msgQId, 0, 0, 0, 0, 0, 0, 0, 0, 0);
return;
}
下载地址
https://pan.baidu.com/s/1CskUTsGYrTyVAJmZ4JEyNQ
提取码:m9yi
有问题的话,先动手试一试
这正是
内部数据要传递 互斥同步多考虑
消息队列最常用 轻松使用看示例
我是泰山 专注VX好多年!
一起学习 共同进步!