Does thread_local! guarantee to call drop()?

I tested for a while, and it looks to me that the variable in thread_local! will be dropped when the thread finished.

Can I rely on this feature? If I remembered right, in C++, destructor of a local_thead is allowed to not get called by standard. And so does #[thread_local] feature in Rust.

And if I can rely on this feature, how does thread_local! do the magic (I expand the macro, and it uses #[thread_local] underlying, and some sort of lazy initialization facilities)?

No.

2 Likes

But the doc said yes:

Initialization is dynamically performed on the first call to with within a thread, and values that implement Drop get destructed when a thread exits. Some caveats apply, which are explained below.

And the blow caveats seems to warn me about behaviors when the main thread exits, which I can accept in my case.

Do I miss anything?

Platform-specific behavior

Note that a “best effort” is made to ensure that destructors for types stored in thread local storage are run, but not all platforms can guarantee that destructors will be run for all types in thread local storage. For example, there are a number of known caveats where destructors are not run:

  1. On Unix systems when pthread-based TLS is being used, destructors will not be run for TLS values on the main thread when it exits. Note that the application will exit immediately after the main thread exits as well.

  2. On all platforms it’s possible for TLS to re-initialize other TLS slots during destruction. Some platforms ensure that this cannot happen infinitely by preventing re-initialization of any slot that has been destroyed, but not all platforms have this guard. Those platforms that do not guard typically have a synthetic limit after which point no more destructors are run.

  3. When the process exits on Windows systems, TLS destructors may only be run on the thread that causes the process to exit. This is because the other threads may be forcibly terminated

That list is not necessarily exhaustive

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.