Freertos中messageQueue 用法
信号量Semaphore和互斥量mutex,只能用于进程间的同步,并不能传递更多的数据。
在freertos,提供了messageQ,用来在实现进程同步的同时,传递数据。
进程间通信,或者ISR和TASK之间通信,如果没有messageQ,则只能通过全局变量来进行,但是这有个问题,就是资源管理的问题。
freertos,提供了messageQ来替代全局变量传递数据。
当消息被填充到messageQ中时,是复制了一个副本的,这样做的代价是,数据复制的CPU时间消耗,但是带来的好处是,数据存放在专属位置,与原始缓冲区无关。如果向将原始缓冲区传递给其他进程,则只需要将缓冲区的指针发送到消息队列中即可。队列中只需要存放指针副本,节省了空间。
messageQ是OS的公共资源,它不属于某个特定的进程,任何进程都可以向队列发送消息,或者提取消息。
以下,将消息队列简称为队列,freertos中,也是简称为Queue的。
添加定义:
void *Mailbox = NULL;
struct MessageQueueAttr_t Msg={NULL,0,NULL,0,NULL,0};
在mainthread中创建:
NetworkMailbox = MessageQueueNew(SIG_NET_MSG_NUM + 5, sizeof(Msg), &Msg);
thread使用:
while(1)
{
/* the thread shall be blocked in the "MessageQueueGet", but timeout after xx seconds to handle the health monitor and retry of connection. */
if (MessageQueueGet(Mailbox, &Msg, NULL, 1000) == osOK) //response less than 1 second
{
switch((Msg_t)(Msg.attr_bits))
{
case 1:
dowork();
default:
break;
}
}
在其他thread中向mailbox抛消息:
void NotifyThread(MessageQueueAttr_t* msg)
{
if (MessageQueuePut(Mailbox,msg, 0, 0) != osOK)
{
PRINTF("msg can not be post!\r\n");
}
}
例如:
首先申明个信号量的全局变量
SemaphoreHandle_t xBinarySemaphore;
然后在main函数中创建信号量
int main(void)
{
...
xBinarySemaphore = xSemaphoreCreateBinary();
...
}
void Task_Producer(void const * argument)
{
//生产者任务负责生产数据并给予信号量
for( ;; )
{
...
if(true==produce_some_data())
{
xSemaphoreGive(xBinarySemaphore);
}
...
}
}
void Task_Consumer(void const * argument)
{
//消费者任务等待获取信号量并进行数据处理
for( ;; )
{
xSemaphoreTake( xBinarySemaphore, portMAX_DELAY );
//下面是对数据的处理函数
...
}
}
此例子为转载。
1813



被折叠的 条评论
为什么被折叠?



