Mutex Task Synchronization
In the Linux mutex example (just as in the eCos example), two
tasks share a common variable called gSharedVariable. One task increments the
global variable at a set interval, and the other task decrements the
variable at a set interval. The mutex protects the shared
variable.
The function main starts by
creating the mutex, sharedVariableMutex, by calling the function
pthread_mutex_init. Because the
default attributes are used in the mutex creation, NULL is passed in as the second parameter. In
Linux, mutexes have attributes that you can set using the second
parameter, but we won’t use them in this book, so we’ll just pass
NULL.
Lastly, the two tasks incrementTask and decrementTask are created. It is important to
create the mutex before creating the tasks that use it, because
otherwise the tasks could crash the program.
#include <pthread.h> pthread_mutex_t sharedVariableMutex; int32_t gSharedVariable = 0; /********************************************************************** * * Function: main * * Description: Main routine for the Linux mutex example. This * function creates the mutex and then the increment and * decrement tasks. * * Notes: * * Returns: 0. * **********************************************************************/ int main(void) { /* Create the mutex for accessing the shared variable using the * default attributes. */ pthread_mutex_init(&sharedVariableMutex, NULL); /* Create the increment and decrement tasks using the default task * attributes. ...