实验目的:使用二值信号量完成任务间的同步
实验设计:任务task00定时释放二值信号量,任务task01获取二值信号量,接收到信号量就进行相应的动作。
测试代码:
代码语言:javascript复制/* task00 info */
configSTACK_DEPTH_TYPE Task00_STACK_SIZE = 5;
UBaseType_t Task00_Priority = 1;
TaskHandle_t Task00_xHandle;
/* task01 info */
configSTACK_DEPTH_TYPE Task01_STACK_SIZE = 5;
UBaseType_t Task01_Priority = 2;
TaskHandle_t Task01_xHandle;
//二值信号量
SemaphoreHandle_t BinarySemaphore;
void vTask00_Code(void *para)
{
static unsigned int cnt = 0;
BaseType_t err = pdTRUE;
for (;;)
{
PRINT(" task00 cnt %u...", cnt );
err = xSemaphoreGive(BinarySemaphore);
if (err != pdTRUE)
PRINT("BinarySemaphore give failed!n");
vTaskDelay(2000);
}
}
void vTask01_Code(void *para)
{
static unsigned int cnt = 0;
BaseType_t err = pdTRUE;
for (;;)
{
xSemaphoreTake(BinarySemaphore, portMAX_DELAY);
PRINT(" task01 cnt %u...", cnt );
vTaskDelay(500);
}
}
void test_BinarySemaphore()
{
BinarySemaphore = xSemaphoreCreateBinary();
if (xTaskCreate(vTask00_Code, "task00 task",
Task00_STACK_SIZE, NULL, Task00_Priority,
&Task00_xHandle) != pdPASS)
{
PRINT("creat task00 failed!n");
}
if (xTaskCreate(vTask01_Code, "task01 task",
Task01_STACK_SIZE, NULL, Task01_Priority,
&Task01_xHandle) != pdPASS)
{
PRINT("creat task01 failed!n");
}
}
void creat_task(void)
{
test_BinarySemaphore();
// test_queue();
}
编译,运行:
代码语言:javascript复制$ ./build/freertos-simulator
task00 cnt 0...
task01 cnt 0...
task00 cnt 1...
task01 cnt 1...
task00 cnt 2...
task01 cnt 2...
可以看出,任务task01等到了信号量之后才会执行。