Skip to content

Conversation

ysbaddaden
Copy link
Contributor

@ysbaddaden ysbaddaden commented Sep 26, 2025

This is an alternative to #16029 that uses a static "container type" instead of a table of void pointers. It roughly moves hard coded values from Thread.current into a dedicated type (allocated when needed) and relies on a macro to generate some code.

It has some advantages, most notably a much simpler implementation and the ability to store any type (not just pointers and nilable references).

It also has some disadvantages, for example it depends on the macro and we lose flexility (must use the generated class method, can only create globals, no runtime dynamism), any declared thread local will grow the container type regardless of actual usage, which in turn requires to set the destructor callback to when we set the TLS... though now that I think about it, I should just use a wrapper class with a finalizer instead 🤦

Credits where its due: the initial idea is from @BlobCodes. See #15616 (comment) and #15889.

Relies on a macro to inject typed instance variables into the container,
and optional destructors as class variables. The overall design is very
simple and accessing a thread local is basically dereferencing the
actual thread local and accessing an ivar.

One drawback is that the compiler doesn't drop unused ivars, so as soon
as an executable needs a thread local, it will allocate the whole type,
even though the program only uses a few of them. Since we don't intent
to have lots of thread locals, this ain't much of an issue.

Another drawback is that destructors will always be registered, whatever
if we actually need the thread local, which may lead to always link
libpcre2 for example, because the destructors will link the external
free symbols, which can be problematic. Maybe weak symbols could help?
Fixes the main drawback of this approach by setting the destructor
callback when we set the thread local, so the destructor will only be
set if the program uses the thread local.
@ysbaddaden ysbaddaden self-assigned this Sep 26, 2025
@ysbaddaden ysbaddaden closed this Sep 27, 2025
@ysbaddaden ysbaddaden deleted the feature/custom-thread-local-storage-with-container-type branch September 27, 2025 18:09
@ysbaddaden
Copy link
Contributor Author

Superseded by #16173.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant