Threads Lifecycle

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

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_CFG_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 CH_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).

More articles and guides are available on the technical wiki.

learn more

Need Tutorials?

Try the video tutorials and guides on Play Embedded.

learn more

Need Support?

The forums is the best place, registration required.

learn more