Skip to Main Content
Programming Embedded Systems, 2nd Edition
book

Programming Embedded Systems, 2nd Edition

by Michael Barr, Anthony Massa
October 2006
Intermediate to advanced content levelIntermediate to advanced
336 pages
9h 13m
English
O'Reilly Media, Inc.
Content preview from Programming Embedded Systems, 2nd Edition

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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming with STM32: Getting Started with the Nucleo Board and C/C++

Programming with STM32: Getting Started with the Nucleo Board and C/C++

Donald Norris

Publisher Resources

ISBN: 0596009836Supplemental ContentErrata Page