Releasing memory in thread if the main thread panics

I use thread::spawn in the main thread to spawn a new thread that allocates some memory and does some work. Now I have the situation that the main thread might panic. As intended, the entire process ends and if I read the documentation correctly, any destructors should be called. But is this also true for the spawned thread if the panic is raised in the main thread?

Valgrind shows that there still is memory “possibly lost” and “still reachable”. Will this eventually be free’d? Do I need to do something to ensure that?


If the main thread panics then the entire process exits, so the OS will release all resources held by the process.

1 Like

There are no guarantees about threads unwinding gracefully before process exit. Theoretically every thread could be busy running loop {} and never be able to jump to any destructor code.

You could try wrapping code of the main thread in catch_unwind(), the tell your threads (in your application-specific way, e.g. via crossbeam-channel) that they should wrap up their work, and thread.join() them.

1 Like