Chris O'Byrne - YAVRTOS

Using mutexes

A mutex is used to ensure that only one task is using a shared resource at any one time.

Example - sharing I/O pins

Given that microcontrollers only have a limited number of I/O pins, it is common for pins to be dual-purpose.

mutex_t pin_mutex;

void task1(void *p) {
        ...
        // task 1 now needs to use the dual-purpose pins
        lock_on(&pin_mutex);
        // we now "own" the mutex, so we "own" the pins
        do_stuff_with_the_dual_purpose_pins();
        // release the pins
        lock_off(&pin_mutex);
        ...
}

void task2(void *p) {
        ...
        // task 2 now needs to use the dual-purpose pins
        lock_on(&pin_mutex);
        // we now "own" the mutex, so we "own" the pins
        do_other_stuff_with_the_dual_purpose_pins();
        // release the pins
        lock_off(&pin_mutex);
        ...
}

YAVRTOS and YAVRTOS documentation Copyright © 2007-2008 Chris O'Byrne. Email - chris <at> obyrne <dot> com