Mutexes, Name, Synopsis – Comtrol eCos User Manual
Page 65: Description

Mutexes
Name
cyg_mutex_init, cyg_mutex_destroy, cyg_mutex_lock, cyg_mutex_trylock,
cyg_mutex_unlock, cyg_mutex_release, cyg_mutex_set_ceiling,
cyg_mutex_set_protocol
— Synchronization primitive
Synopsis
#include
<
cyg/kernel/kapi.h
>
void cyg_mutex_init(cyg_mutex_t* mutex);
void cyg_mutex_destroy(cyg_mutex_t* mutex);
cyg_bool_t cyg_mutex_lock(cyg_mutex_t* mutex);
cyg_bool_t cyg_mutex_trylock(cyg_mutex_t* mutex);
void cyg_mutex_unlock(cyg_mutex_t* mutex);
void cyg_mutex_release(cyg_mutex_t* mutex);
void cyg_mutex_set_ceiling(cyg_mutex_t* mutex, cyg_priority_t priority );
void cyg_mutex_set_protocol(cyg_mutex_t* mutex, enum cyg_mutex_protocol protocol/);
Description
The purpose of mutexes is to let threads share resources safely. If two or more threads attempt to manipulate a data
structure with no locking between them then the system may run for quite some time without apparent problems,
but sooner or later the data structure will become inconsistent and the application will start behaving strangely and
is quite likely to crash. The same can apply even when manipulating a single variable or some other resource. For
example, consider:
static volatile int counter = 0;
void
process_event(void)
{
...
counter++;
}
Assume that after a certain period of time
counter
has a value of 42, and two threads A and B running at the
same priority call
process_event
. Typically thread A will read the value of
counter
into a register, increment
this register to 43, and write this updated value back to memory. Thread B will do the same, so usually
counter
will end up with a value of 44. However if thread A is timesliced after reading the old value 42 but before writing
back 43, thread B will still read back the old value and will also write back 43. The net result is that the counter
only gets incremented once, not twice, which depending on the application may prove disastrous.
65