NRF fundamental course lesson 8 exercise 1

Hello,


I have a question about the NRF SDK fundamental lesson 8 exercise 1. In the code below get_access and release_access are executed in different threads. The semaphore is initialized with count of 10. Since the semaphore count is greater than zero, would it be possible that the thread executing get_access attempts to modify available_instance_count when release_access is modifying it too? I tried to run the code in this lesson multiple times but didn’t notice any corruption of available_instance_count. However, it’s not clear for me why it does not happen. I would appreciate any clarification.


Thanks,
Sam

// Function for getting access of resource
void get_access(void)
{
    /* STEP 10.1 - Get semaphore before access to the resource */
    k_sem_take(&instance_monitor_sem, K_FOREVER);

    /* STEP 6.1 - Decrement available resource */
    available_instance_count--;
    printk("Resource taken and available_instance_count = %d\n",  available_instance_count);
}

// Function for releasing access of resource
void release_access(void)
{
    /* STEP 6.2 - Increment available resource */
    available_instance_count++;
    printk("Resource given and available_instance_count = %d\n", available_instance_count);

    /* STEP 10.2 - Give semaphore after finishing access to resource */
    k_sem_give(&instance_monitor_sem);
}
Parents
  • That is great observation Sam, I wrote this lesson and I see that there is room for improvement here. Theoretically, available_instance_count is prone to corruption

    I think you understand the mutual exclusion thing properly. I think we got lucky here are the window where the race condition happens is relatively small and somehow the compiler managed to access this variable in an atomic way. I should have just made this variable atomic to remove the possible race condition window.

Reply
  • That is great observation Sam, I wrote this lesson and I see that there is room for improvement here. Theoretically, available_instance_count is prone to corruption

    I think you understand the mutual exclusion thing properly. I think we got lucky here are the window where the race condition happens is relatively small and somehow the compiler managed to access this variable in an atomic way. I should have just made this variable atomic to remove the possible race condition window.

Children
No Data
Related