TLS variable for only one thread
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Sat Feb 15 10:09:39 UTC 2025
On Saturday, February 15, 2025 12:53:17 AM MST IchorDev via Digitalmars-d-learn wrote:
> If I have a module-level variable, each thread sees a different
> value for it. But how would I create a module-level variable that
> can only be accessed by one thread? Do I have to give it its own
> module?
I think that you need to be clearer about what you're trying to do. If a
module-level variable is not shared, __gshared, or immutable, then each
thread gets a completely separate variable, and no other thread has access
to that object unless you do something to pass it to another thread (which
would involve casting to shared or immutable and calling and then using
something like std.concurrency to pass it across), and the only way to give
another thread access to the variable itself would be to take its address
and cast the pointer to shared or immutable to be able to pass it across
threads. The variable itself is restricted to a single thread, so it's
already the case that no other threads have access to a non-shared variable.
Now, if you mean that you want the object to literally be in thread-local
storage, the language has no support for that, and I don't know quite what
you'd buy by having that, since it's already guaranteed that variables
aren't shared across threads unless you're using shared, __gshared, or
immutable to make it happen. You'd likely to have to use whatever OS
facilities are provided in C to deal with TLS. Either way, D itself doesn't
do anything with TLS, much as we often talk about non-shared variables being
thread-local.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list