Detour: Using the Same Function for Different Tasks

In the previous MUTEX example, task1 and task2 are basically the same except for the strings being used. While the following is a contrived example, often a single function can be used for multiple tasks:

 

void task(unsigned arg0)

      {

      char *text[2] = {

            “Hello World”,

            “I am alive!”

      };

      char *s = text[arg0];

 

      while (1)

            {

            int x = 0;

           

            REXIS_MutexLock(mutex1, 0);

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

            REXIS_MutexUnlock(mutex1);

            }

      }

 

Obviously, in real code, the task should perform argument checking to ensure that the arguments are not out of range. The task creates a function, then invokes the task function with different initial arguments:

 

      REXIS_TaskCreate(“task 1”, task, 0, 0, 0);

      REXIS_TaskCreate(“task 2”, task, 0, 0, 1);

 

“arg0” can be of any type, typecasted to unsigned int if needed. For example, a function may take a pointer to different SPI port. With Cortex-M, as a pointer and an unsigned int has the same number of bits (32), so you can cast a pointer value to an int and back again without losing any information.