MUTEX Example

A MUTEX (Mutually Exclusive access to shared resources) provides for controlled access to a shared resource. For example, if you have two tasks writing to the UART:

 

void task1(unsigned arg0)

      {

      while (1)

            {

            int x = 0;

           

            printf(“Hello World %d\n”, x);

            }

      }

 

void task2(unsigned arg0)

      {

      while (1)

            {

            int x = 0;

           

            printf(“I am alive! %d\n”, x);

            }

      }

 

Depending on various factors such as scheduling frequency, task priorities, etc., the chances are that the resulting output would be a jumble of characters sent from both tasks. The fix for this type of issue is to use a MUTEX:

 

extern REXIS_MUTEX *mutex1;

 

void task1(unsigned arg0)

      {

      while (1)

            {

            int x = 0;

           

            REXIS_MutexLock(mutex1, 0);

            printf(“Hello World %d\n”, x);

            REXIS_MutexUnlock(mutex1);

            }

      }

 

void task2(unsigned arg0)

      {

      while (1)

            {

            int x = 0;

           

            REXIS_MutexLock(mutex1, 0);

            printf(“I am alive! %d\n”, x);

            REXIS_MutexUnlock(mutex1);

            }

      }

 

      … // somewhere in main() or earlier

            mutex1 = REXIS_MutexCreate();

 

The MUTEX controls access to the output stream, and when it is run the output will look much saner, because once a task obtains the lock on a MUTEX, the second task will wait until the first task has finished and unlocked the MUTEX before the second task can lock the MUTEX itself.