一、cube配置
二、接口介绍:
xSemaphoreGive() and xSemaphoreTake()与二值信号量接口一致,只不过填入的是计数信号量的句柄myCountingSem01Handle。
如果想知道当前的信号量的个数可使用uxSemaphoreGetCount(myCountingSem01Handle)
三、程序编写
3.1当阻塞时间为0时
osSemaphoreDef(myCountingSem01);
myCountingSem01Handle = osSemaphoreCreate(osSemaphore(myCountingSem01), 3);
/*Cube配置生成计数信号量默认填满状态(默认有3个信号量)*/
...
void T4(void const * argument)
{
/* USER CODE BEGIN T4 */
/* Infinite loop */
for(;;)
{
Key_Check();
if(keyvalue == KEY0) {
if( xSemaphoreGive(myCountingSem01Handle) == pdTRUE) {
printf("give complete\r\n");
}
else {
printf("give error\r\n");
}
keyvalue = UNKNOW;
}
if(keyvalue == KEY1) {
if(xSemaphoreTake(myCountingSem01Handle, 0) == pdTRUE) {
printf("take complete\r\n");
}
else {
printf("take error\r\n");
}
keyvalue = UNKNOW;
}
}
/* USER CODE END T4 */
}
分析:Cube默认填满因此take成功三次再一次会失败,give连续三次成功因为count为3...
3.2当阻塞时间为MAX时
void T3(void const * argument)
{
for(;;)
{
Key_Check();
if(keyvalue == KEY0) {
if( xSemaphoreGive(myCountingSem01Handle) == pdTRUE) {
printf("give complete\r\n");
}
else {
printf("give error\r\n");
}
keyvalue = UNKNOW;
}
}
/* USER CODE END T3 */
}
...
void T4(void const * argument)
{
/* USER CODE BEGIN T4 */
/* Infinite loop */
for(;;)
{
Key_Check();
if(keyvalue == KEY1) {
if(xSemaphoreTake(myCountingSem01Handle, portMAX_DELAY) == pdTRUE) {
printf("take complete\r\n");
}
else {
printf("take error\r\n");
}
keyvalue = UNKNOW;
}
}
/* USER CODE END T4 */
}
分析:成功提取三次后再次按下TAKE键由于阻塞时间为portMAX_DELAY故T4任务进入阻塞态一直阻塞,直到接收到新的信号量,接下来按下GIVE键发现串口打印结果为gake说明这边释放那边接收且均成功了两个printf(... complete)语句同时执行,故现在是扯平了的状态因此能够再成功释放信号三次