Taking and giving semaphore inside a task
Posted: Thu Dec 02, 2021 10:41 am
Hello. In my program, I am parsing incoming BLE messages and based on those messages, I must activate a one shot RTOS task
some pseudo code:
Whenever any of those 3 tasks are started, I must not allow any other tasks to start untill this one has finished. I may still be able to send BLE command and my parser will try to start a task but it must fail if there is a running task already.
I have decided to use semaphore for that.
Inside each task at the beggining, I check if this semaphore is free. If it is free, I do some stuff inside a task and it deletes itself. If I detect that the semaphore is already taken by someone else, I delete the task immediately.
However, I notice that everytime I try to start any of the task, it just says that semaphore is taken by someone else even though it is definately not since I have just sent the first command after the device reset.
Is there something I am misunderstanding about the semaphores? According to how I understand it, this should just simply work
some pseudo code:
Code: Select all
if(ble_command == 1){
xTaskCreate(task1,"task1",10000,&global_message,1,&task1_handle);
}
elseif(ble_command == 2){
xTaskCreate(task2,"task2",10000,&global_message,1,&task2_handle);
}
else{
xTaskCreate(task3,"task3",10000,&global_message,1,&task3_handle);
}
I have decided to use semaphore for that.
Code: Select all
spi_long_task_mutex = xSemaphoreCreateBinary();
Inside each task at the beggining, I check if this semaphore is free. If it is free, I do some stuff inside a task and it deletes itself. If I detect that the semaphore is already taken by someone else, I delete the task immediately.
Code: Select all
void task1(void* param){
if(xSemaphoreTake(spi_long_task_mutex,100)==pdTRUE){
for(;;)
{
printf("hello world \n");
xSemaphoreGive(spi_long_task_mutex);
vTaskDelete(0);
}
}
else{
printf("semaphore is taken by someone else \n");
vTaskDelete(0);
}
}
Is there something I am misunderstanding about the semaphores? According to how I understand it, this should just simply work