信号量同样是RTOS学习中很重要的一节,信号量可以用在共享资源或者同步任务中,对执行权的控制,谁拥有信号量谁拥有执行权,在freeRTOS中信号量和互斥量有点不同,关于信号量的更多描述可以参考官网相关网页描述。每一个信号量都需要少量的内存来保持信号量的状态,那么这内存是如何分配的呢,这根据使用的API函数会有所不同,创建信号量主要有xSemaphoreCreateBinary()和xSemaphoreCreateBinaryStatic() ,使用前者创建信号量,则所需的内存将会自动从freeRTOS的堆上分配,如果是使用后者创建的信号量,则所需内存由应用程序分配,且后者API需要另外的参数,在编译的时候静态分配给信号量,前者则是动态分配,关于静态分配和动态分配可以参阅freeRTOS官网详细信息。
我们看一下两种API创建信号量使用的例子
Example usage:
SemaphoreHandle_txSemaphore;
void vATask( void *pvParameters )
{
/* Attempt to create a semaphore. */
xSemaphore = xSemaphoreCreateBinary();
if( xSemaphore == NULL )
{
/* There was insufficient FreeRTOS heap available for thesemaphore to
be created successfully. */
}
else
{
/* The semaphore can now be used. Its handle is stored inthe
xSemahore variable. Calling xSemaphoreTake() on the semaphorehere
will fail until the semaphore has firstbeen given. */
}
}
Example usage:
SemaphoreHandle_t xSemaphore = NULL;
StaticSemaphore_t xSemaphoreBuffer;
void vATask( void * pvParameters )
{
/* Create a binary semaphore without using any dynamic memory
allocation. The semaphore's data structures will be saved into
the xSemaphoreBuffer variable. */
xSemaphore = xSemaphoreCreateBinaryStatic( &xSemaphoreBuffer );
/* The pxSemaphoreBuffer was not NULL, so it is expected that the
handle will not be NULL. */
configASSERT( xSemaphore );
/* Rest of the task code goes here. */
}
在公众号前面的文章中我们在kv46上移植的demo有官方提供的信号量的例程,推荐大家下载最新版的v9.0.0源码学习,新更新的特性和内容在源码包里都有提及,研究例程是最好的学习方法。这里只是给大家简单介绍使用方法,更加详细的内容还需自己仔细阅读源码和官方参考资料。如果还有不会移植的猿友,欢迎参考公众号里的相关文章。