1、 介绍计数信号量
①使用计数信号要包含#include "semphr.h"头文件
2、 创建give任务和take任务,创建最大信号量为5和有效值为5的计数信号量。
void m_create_count_sem(void)
{
CountSem_Handle = xSemaphoreCreateCounting(5,5);
// CountSem_Handle = xQueueCreateCountingSemaphore( 5,5 );
if(NULL != CountSem_Handle)
LOG_BLE("create count sem task ok\r\n");
xTaskCreate(take_task, "take_task", configMINIMAL_STACK_SIZE + 200, NULL, 2, &take_task_handle);
xTaskCreate(give_task, "give_task", configMINIMAL_STACK_SIZE + 200, NULL, 2, &give_task_handle);
}
3、 编写内存的测试任务入口函数
#include "semphr.h"
#ifndef TAG_BLE
#define LOG_BLE(...)
#endif
static SemaphoreHandle_t CountSem_Handle =NULL;
static TaskHandle_t take_task_handle;
static TaskHandle_t give_task_handle;
static void take_task (void * pvParameter)
{
BaseType_t xReturn = pdPASS;
uint8_t button1_sta=0;
while (true)
{
if (READ_BUTTON1_P11() == BUTTON_PUSH)
{
if (button1_sta==0)
{
xReturn = xSemaphoreTake(CountSem_Handle,0);
if ( pdTRUE == xReturn )
{
LOG_BLE("take count sem ok\n");
LOG_BLE("current left count sem:%d\n",uxSemaphoreGetCount(CountSem_Handle));
} else
{
LOG_BLE("take count sem error\n")
}
button1_sta = 1;
}
} else
{
button1_sta = 0;
}
vTaskDelay(20);
}
}
static void give_task (void * pvParameter)
{
BaseType_t xReturn = pdTRUE;
uint8_t button1_sta=0;
while (true)
{
if (READ_BUTTON2_P12() == BUTTON_PUSH)
{
if (button1_sta==0)
{
xReturn = xSemaphoreGive(CountSem_Handle);
TOGGLE_LED13();
if ( pdTRUE == xReturn )
{
LOG_BLE("give count sem ok\n");
LOG_BLE("current left count sem:%d\n",uxSemaphoreGetCount(CountSem_Handle));
} else
{
LOG_BLE("give count sem error\n");
}
button1_sta = 1;
}
} else
{
button1_sta = 0;
}
vTaskDelay(20);
}
}
4、实验说明和现象
①通过give任务,每按下一次按键将释放一次信号量且显示当前剩余有效信号,当有效信号量为5时释放失败。
②通过take任务,每按下一次按键将获取一次信号量且显示当前剩余有效信号,当有效信号量为0时获取失败。