Thread-local Member Variables?

dsimcha dsimcha at yahoo.com
Wed Jan 13 19:18:45 PST 2010


== Quote from Craig Black (craigblack2 at cox.net)'s article
> "dsimcha" <dsimcha at yahoo.com> wrote in message
> news:hikj7a$18lq$1 at digitalmars.com...
> > Should there be a way, in D, to create a variable that's local to both a
> > thread and a class instance?  For example:
> >
> > class Foo {
> >    __thread uint num;
> > }
> >
> > num would basically be a reference to thread-local storage, with a new one
> > created for every instance of Foo.  Is there a (non-hacky) way to do this
> > already?
> I need the same feature, but I don't really see an efficient way to do this
> in the language itself.  It is probably better relegated to a template.
> Also, rather than giving all threads access, I would limit access to each
> "thread-local" variable to a thread pool of constant size.  In other words,
> only threads in a particular thread pool could access this variable.  This
> way, the variable can be represented as an array that never needs resizing,
> where each thread in the pool has an index to an element in the array.
> -Craig

Yea, this is probably something that should be implemented in a library, not the
core language.  I've been thinking about it, but I don't see any way to do it
**efficiently**.  Some obvious but flawed ways:

1.  In each class instance, have a hash table of variable[thread ID].  Problem:
Requires synchronization when adding a thread.

2.  In each class declaration have a static thread-local hash table of
variable[class instance].  The problem with this is that this creates a reference
to the class instance, which never gets GC'd.  Even with weak references, the hash
table entries would eventually need to be cleaned up.




More information about the Digitalmars-d mailing list