A lower priority task starting first ?

diptopal wrote on Thursday, August 22, 2013:

Here is a relevant part of the code

**xSemaphoreHandle employee_signal = 0;

void employee_task() {

;

}

void boss(void *p){
  for(;;){
      LPC_printf(“1\n\r”);
      xSemaphoreGive(employee_signal);
  LPC_printf(“3\r\n”);
  vTaskDelay(2000);
 
  }
}

void employee(void *p){
   for(;;){
       if(xSemaphoreTake(employee_signal, portMAX_DELAY) == pdTRUE ){
   employee_task();
   LPC_printf(“2\n\r”);
   }
   }

}

int main (void) {

vSemaphoreCreateBinary(employee_signal);
    LPC_UART0->IER = IER_THRE | IER_RLS;
SystemInit();                         /* initialize clocks */
  UARTInit(0, 38400); /* baud rate setting */
  UARTInit(1, 38400); /* baud rate setting */
xTaskCreate( boss,  ( signed char* ) “t1”,  1024, NULL, 1, NULL  );
xTaskCreate( employee,  ( signed char* ) “t2”,  1024, NULL, 1, NULL  );
vTaskStartScheduler();
    return 0;
}**

I am expecting the boss task to start printing first, but as I can see, once immediately after the program starts the employee task is printing once to the console, then it falls into the right sequence. I am expecting the boss task to start instead, give a semaphore to the employee task and then the employee task to wake up. Pasting a part of the output here. This is on LPC1768 hardware, I hope I have configured the RTOS properly.

2  <- This should not be here
1 <- The printing should start from here
2
3
1
2
3
1
2
3

I am only able to avoid this situation id I am making the priority od the boss task higher. Then I am getting the correct output. How is the employee task printing first when the boss has not even started and given it a semaphore?

diptopal wrote on Thursday, August 22, 2013:

I am sorry, the topic should have been something else, like how can my task print even without getting a Semaphore?

edwards3 wrote on Thursday, August 22, 2013:

The semaphore is created so the first take will pass. If you take the semaphore immediately after you create it (before your tasks start using it) then I think it will work the way your code expected it to.

mdkendall wrote on Thursday, August 22, 2013:

Mutexes and binary semaphores are created in the already-given state, so the fact that your first take operation succeeds is expected behaviour.

For it to work as you want, you must take the semaphore immediately after creating it.