Valid contexts – Comtrol eCos User Manual
Page 84
Spinlocks
get another chance to run and release the spinlock. Even if the two threads were running at the same priority, the
one attempting to claim the spinlock would spin until it was timesliced and a lot of cpu time would be wasted. If an
interrupt handler tried to claim a spinlock owned by a thread, the interrupt handler would loop forever. Therefore
spinlocks are only appropriate for SMP systems where the current owner of a spinlock can continue running on a
different processor.
Before a spinlock can be used it must be initialized by a call to
cyg_spinlock_init
. This takes two arguments,
a pointer to a
cyg_spinlock_t
data structure, and a flag to specify whether the spinlock starts off locked or
unlocked. If a spinlock is no longer required then it can be destroyed by a call to
cyg_spinlock_destroy
.
There are two routines for claiming a spinlock:
cyg_spinlock_spin
and
cyg_spinlock_spin_intsave
. The
former can be used when it is known the current code will not be preempted, for example because it is running in
an interrupt handler or because interrupts are disabled. The latter will disable interrupts in addition to claiming the
spinlock, so is safe to use in all circumstances. The previous interrupt state is returned via the second argument,
and should be used in a subsequent call to
cyg_spinlock_clear_intsave
.
Similarly
there
are
two
routines
for
releasing
a
spinlock:
cyg_spinlock_clear
and
cyg_spinlock_clear_intsave
. Typically the former will be used if the spinlock was claimed by a call to
cyg_spinlock_spin
, and the latter when
cyg_spinlock_intsave
was used.
There are two additional routines.
cyg_spinlock_try
is a non-blocking version of
cyg_spinlock_spin
: if
possible the lock will be claimed and the function will return
true
; otherwise the function will return immediately
with failure.
cyg_spinlock_test
can be used to find out whether or not the spinlock is currently locked. This
function must be used with care because, especially on a multiprocessor system, the state of the spinlock can
change at any time.
Spinlocks should only be held for a short period of time, and attempting to claim a spinlock will never cause a
thread to be suspended. This means that there is no need to worry about priority inversion problems, and concepts
such as priority ceilings and inheritance do not apply.
Valid contexts
All of the spinlock functions can be called from any context, including ISR and DSR context. Typically
cyg_spinlock_init
is only called during system initialization.
84