计数型信号量
又叫数值信号量。用户只需要关心信号量存了多少数据量。
应用:
相关API函数
函数 | 描述 |
---|
xSemaphoreCreateCounting() | 动态方法创建计数型信号量 | xSemaphoreCreateCountingStatic() | 静态方法创建计数型信号量 |
使用动态方法创建,函数原型。
SemaphoreHandle_t xSemaphoreCreateCounting(UBaseType_t uxMaxCount,
UBaseType_t uxInitialCount )
uxMaxCount最大计数值,uxInitialCount计数初始值。SemaphoreHandle_t成功则返回句柄。
释放信号量
函数 | 描述 |
---|
xSemaphoreGive() | 任务级信号量释放(除递归信号量均使用这个) | xSemaphoreGiveFromISR() | 中断级信号量释放(除递归信号量均使用这个) |
获取信号量
函数 | 描述 |
---|
xSemaphoreTake() | 任务级信号量获取(需要阻塞时间) | xSemaphoreTakeFromISR() | 中断级信号量获取(不需要阻塞时间) |
返回信号量的值。
信号量句柄
SemaphoreHandle_t SemphrHandle; // 信号量句柄
创建信号量
SemphrHandle = xSemaphoreCreateCounting(10, 0);
if(SemphrHandle == NULL)
{
printf("xSemaphoreCreateCounting Failed!\r\n");
}
任务一当按键被按键则发送信号量,任务二阻塞接收。
void task1_task(void *pvParameters)
{
u8 key_val = 0;
BaseType_t err;
while(1)
{
key_val = KEY_Scan(0);
if(key_val&&SemphrHandle)
{
LED0=~LED0;
err = xSemaphoreGive(SemphrHandle);
if(err != pdTRUE)
printf("xSemaphoreGive Failed!\r\n");
}
vTaskDelay(10);
}
}
void process_task(void *pvParameters)
{
BaseType_t cnt = 0;
BaseType_t err;
while(1)
{
if(SemphrHandle)
{
err = xSemaphoreTake(SemphrHandle,portMAX_DELAY);
if(err == pdTRUE)
{
LED1=~LED1;
cnt = uxSemaphoreGetCount(SemphrHandle);
printf("Semaphore cnt = %ld\r\n",cnt);
}
}
else
{
printf("SemphrHandle = NULL\r\n");
}
vTaskDelay(500);
}
}
实验现象:
Semaphore cnt = 0
Semaphore cnt = 0
Semaphore cnt = 3
Semaphore cnt = 5
Semaphore cnt = 8
xSemaphoreGive Failed!
Semaphore cnt = 9
xSemaphoreGive Failed!
xSemaphoreGive Failed!
Semaphore cnt = 9
xSemaphoreGive Failed!
Semaphore cnt = 9
xSemaphoreGive Failed!
Semaphore cnt = 9
xSemaphoreGive Failed!
xSemaphoreGive Failed!
Semaphore cnt = 9
xSemaphoreGive Failed!
Semaphore cnt = 9
Semaphore cnt = 8
Semaphore cnt = 7
Semaphore cnt = 6
Semaphore cnt = 5
Semaphore cnt = 4
Semaphore cnt = 3
Semaphore cnt = 2
Semaphore cnt = 1
Semaphore cnt = 0
|