Suspend and resume, Releasing a blocked thread, Valid contexts – Comtrol eCos User Manual

Page 48

Advertising
background image

Thread control

If the application requires delays measured in milliseconds or similar units rather than in clock ticks, some calcula-
tions are needed to convert between these units as described in

Clocks

. Usually these calculations can be done by the

application developer, or at compile-time. Performing such calculations prior to every call to

cyg_thread_delay

adds unnecessary overhead to the system.

Suspend and Resume

Associated with each thread is a suspend counter. When a thread is first created this counter is initialized to 1.

cyg_thread_suspend

can be used to increment the suspend counter, and

cyg_thread_resume

decrements it.

The scheduler will never run a thread with a non-zero suspend counter. Therefore a newly created thread will not
run until it has been resumed.

An occasional problem with the use of suspend and resume functionality is that a thread gets suspended
more times than it is resumed and hence never becomes runnable again. This can lead to very
confusing behaviour. To help with debugging such problems the kernel provides a configuration option

CYGNUM_KERNEL_MAX_SUSPEND_COUNT_ASSERT

which imposes an upper bound on the number of suspend calls

without matching resumes, with a reasonable default value. This functionality depends on infrastructure assertions
being enabled.

Releasing a Blocked Thread

When a thread is blocked on a synchronization primitive such as a semaphore or a mutex, or when it is waiting
for an alarm to trigger, it can be forcibly woken up using

cyg_thread_release

. Typically this will call the

affected synchronization primitive to return false, indicating that the operation was not completed successfully.
This function has to be used with great care, and in particular it should only be used on threads that have been
designed appropriately and check all return codes. If instead it were to be used on, say, an arbitrary thread that is
attempting to claim a mutex then that thread might not bother to check the result of the mutex lock operation -
usually there would be no reason to do so. Therefore the thread will now continue running in the false belief that it
has successfully claimed a mutex lock, and the resulting behaviour is undefined. If the system has been built with
assertions enabled then it is possible that an assertion will trigger when the thread tries to release the mutex it does
not actually own.

The main use of

cyg_thread_release

is in the POSIX compatibility layer, where it is used in the implementation

of per-thread signals and cancellation handlers.

Valid contexts

cyg_thread_yield

can only be called from thread context, A DSR must always run to completion and cannot

yield the processor to some thread.

cyg_thread_suspend

,

cyg_thread_resume

, and

cyg_thread_release

may be called from thread or DSR context.

48

Advertising