Lock-Unlock

If the task does not share variables or data structures with an ISR, you can disable and enable µC/OS-III’s scheduler while accessing the resource, as shown in the listing below.


Accessing a resource with the scheduler locked
          void YourFunction (void) 
          {
              OS_ERR  err;                    (1) 
           
           
              OSSchedLock(&err);              (2) 
              Access the resource;            (3) 
              OSSchedUnlock(&err);            (4) 
          }


OSSchedLock() and OSSchedUnlock() can be nested up to 250 levels deep. The scheduler is invoked only when OSSchedUnlock() is called the same number of times the application called OSSchedLock().Using this method, two or more tasks share data without the possibility of contention. Note that while the scheduler is locked, interrupts are enabled and if an interrupt occurs while in the critical section, the ISR is executed immediately. At the end of the ISR, the kernel always returns to the interrupted task even if a higher priority task is made ready-to-run by the ISR. Since the ISR returns to the interrupted task, the behavior of the kernel is similar to that of a non-preemptive kernel (while the scheduler is locked).

After the scheduler is unlocked, µC/OS-III performs a context switch if a higher priority task is ready-to-run.

µC/OS-III will not allow the user to make blocking calls when the scheduler is locked. If the application were able to make blocking calls, the application would most likely fail.

Although this method works well, you can avoid disabling the scheduler as it defeats the purpose of having a preemptive kernel. Locking the scheduler makes the current task the highest priority task.