phobos / tango / ares

Sean Kelly sean at
Sun Feb 11 00:37:41 PST 2007

Johan Granberg wrote:
> Sean Kelly wrote:
>> kris wrote:
>>> Charles D Hixson wrote:
>>>> I'm not sure whether you were quoting the documentation, or reporting
>>>> your understanding.  If you were quoting the documentation, I think it
>>>> needs editing.
>>>  From the doc: "Please note that the class itself is stateful, and
>>> therefore a single instance is not shareable across multiple threads."
>>> Thus, it is considered unwise to share a single instance of Sprint
>>> across multiple threads. However, multiple threads /can/ share a single
>>> instance if they follow this pattern:
>>> synchronized (GlobalSprint)
>>>               GlobalSprint ("do my formatting", with, these, args);
>>> This is a fairly standard mechanism in D for sharing resources across
>>> threads, and it's what I had referred to.
>> For what it's worth, Tango also provides thread-local storage, and while
>> it isn't ideal from a semantic standpoint (a bona-fide 'local' storage
>> class would be much nicer), it's an option worth considering.  It could
>> be used like so:
>>      auto TLSPrint = new ThreadLocal!(Sprint);
>>      // do this in each thread
>>      TLSPrint.val = new Sprint;
>>      // use the local Sprint instance
>>      TLSPrint.val()( "do my formatting", with, these, args );
>> Accessing a TLS value tyically amounts to a few pointer dereferences so
>> it's far less costly than acquiring a mutex, which may or may not be
>> important to you.
>> As a side-note... Tango currently provides 64 TLS "slots".  This amount
>> is fixed mostly to keep performance as high as possible, but it could
>> easily be increased if it turns out not to be enough.
> What happens when you run out of slots?

An exception is thrown.  Please note that 64 slots doesn't mean each 
thread occupies a separate slot however, but rather than there is 
storage reserved for 64 different thread-local variables.  For a typical 
application, I think this is more than sufficient.

> Would it be possible to have a dynamic amount of slots (doubling whenever
> there is to few)?

Not without involving a mutex.  When a TLS slot is deleted, the 
algorithm visits each thread and nulls out the appropriate slot.  With a 
fixed-size array this just works, but if the array can be resized then 
there's a chance it may be resized at exactly the wrong moment and you 
end up with a segfault.  The ideal scenario would be to use the 
operating system's built-in thread-local storage mechanism, but there is 
no efficient way to make the GC aware of these locations (at least not 
without some clever hacking based on low-level knowledge of how each OS 
actually stored this information, and it is different for every OS). 
The current approach was chosen simply because it was the most general, 
efficient, and reliable.


More information about the Digitalmars-d-learn mailing list