Transient threads: How to release allocated memory automatically?

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: utzig, lbednarz, tfAteba, barthess, RoccoMarco

Posts: 59
Joined: Mon Aug 10, 2015 6:57 am
Has thanked: 6 times
Been thanked: 3 times

Transient threads: How to release allocated memory automatically?

Postby ceremcem » Thu Jan 18, 2018 3:40 am

In the docs, it's clearly stated that `chThdCreateFromHeap()` does not release the allocated memory to the heap but it's a mandatory action if I don't design the application in a wrong way.

There is a `blink()` function that receives a message, turns an output on, waits a little bit and then turns that output off. Every message should be handled in parallel. If I create a static thread per message, it works correctly for only one output. If multiple messages arrive back-to-back for multiple outputs, 3-4 outputs are turned on and MCU freezes.

It experiences a stack overflow since I don't release any of the threads I created. Why should I manually call the `chThdWait()` function as it is blocking (so there seems no point using a thread if I would block the execution?).

The other (and more important) question is, how can I release the allocated memory as soon as the dynamic thread exits?

User avatar
Site Admin
Posts: 13012
Joined: Wed May 27, 2009 8:48 am
Location: Salerno, Italy
Has thanked: 745 times
Been thanked: 621 times

Re: Transient threads: How to release allocated memory automatically?

Postby Giovanni » Thu Jan 18, 2018 8:44 am


The memory can only be deallocated by another thread because one thread cannot free the memory stack where its own stack is. In ChibiOS the memory is deallocated when the thread references counter reaches zero AND the thread is no more running, chThdWait() simply ensures this. References can also be released using chThdRelease() without waiting.

If the counter reaches zero but the thread is still running then it becomes "detached", the memory cannot be freed because there are no more references.

Detached and terminated threads are called zombies.

The only way to free the memory of zombies is to perform a scan using the registry, doing this also cleans up zombies. You may have a thread that periodically (or when triggered) performs a scan.


Return to “General Support”

Who is online

Users browsing this forum: No registered users and 8 guests