Threads Lifecycle

Threads are created and can terminate, when there is memory allocation involved thing may become more complicated.

Thread classes

In ChibiOS/RT threads are divided in two classes:

  • Static threads. The memory used for static threads is allocated at compile time so static threads are always there, there is no management to be done.
  • Dynamic threads. Dynamic threads are allocated at runtime from one of the available allocators.

Freeing threads memory

Dynamic threads create the problem of who is responsible of releasing their memory because a thread cannot dispose its own memory, this is handled in ChibiOS/RT through the mechanism of “thread references”. When the CH_USE_DYNAMIC option is enabled the threads become objects with a reference counter. The memory of a dynamic thread is freed when the last reference to the thread is released while the thread is in its THD_STATE_FINAL state. The following diagram explains the mechanism: As you can see the easiest way to ensure that the memory is released is to make another thread perform a chThdWait() on the dynamic thread.
If all the references to the threads are released while the thread is still alive then the thread goes in a “detached” state and its memory cannot be recovered unless there is a dedicated task in the system that scans the threads through the registry subsystem, scanning the registry has the side effect to release the zombies (detached and then terminated threads).

 
chibios/kb/threads_lifecycle.txt · Last modified: 2011/10/03 20:56 by giovanni
 
Except where otherwise noted, content on this wiki is licensed under the following license:GNU Free Documentation License 1.3