Mutex Task Synchronization
Now we attack the next big job in task management, which is to synchronize tasks. As we saw in Chapter 10, a mutex is a common mechanism for getting two independent tasks to cooperate. For our eCos mutex example, two tasks share a common variableâthe first task incrementing it and the second decrementing it at set intervals. The mutex is used to protect the shared variable.
Before accessing a shared resource, a task takes the mutex; once finished, the task releases the mutex for other tasks to use. Each operating system defines these two operations in its own way. For example, eCos offers lock (taking the mutex) and unlock (releasing the mutex) functions.
To keep track of the multiple tasks waiting on the same mutex, the mutex structure contains a queue of tasks that are waiting on that particular mutex. This queue is typically sorted by priority so the highest-priority task waiting for the mutex executes first. One possible result of releasing the mutex could be to wake a task of higher priority. In that case, the releasing task would immediately be forced (by the scheduler) to give up control of the processor, in favor of the higher-priority task.
The main function, cyg_user_start
, which is shown next, calls the
cyg_mutex_init
function to initialize
mutexes, such as the one weâve named sharedVariableMutex
. This mutex is used to
protect the variable gSharedVariable
. After returning from the mutex initialization call, the mutex is available to the ...
Get Programming Embedded Systems, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.