Threads and Static Data

Craig Black cblack at ara.com
Mon Dec 10 06:57:37 PST 2007


"Robert Fraser" <fraserofthenight at gmail.com> wrote in message 
news:fjip5u$2uud$1 at digitalmars.com...
> Craig Black wrote:
>> I'm in the process of hashing out a design for multi-core support for a 
>> large API developed by myself and a couple other people.  I realized that 
>> static data can be problematic for multiple threads.  In many cases, it 
>> seems that static data should be instantiated on a per-thread basis.  My 
>> solution to this problem is to use a template class called "Threaded" 
>> that instantiates data for each thread.
>>
>> static Threaded!(int) x;
>>
>> Then to access the value, there would have to be a thread ID passed into 
>> it. So to increment the value you would have.
>>
>> int temp = x.get(threadID);
>> x.set(threadID, temp+1);
>>
>> (Or, I guess you could use a pointer.)
>>
>> int *ptr = x.getptr(threadID);
>> (*ptr)++;
>>
>> This solution will do the job, but it is a little clumsy.  This seems 
>> like this is a common problem that warrants better syntax.  Ideally, I 
>> would like to be able access a "threaded" variable just like any other so 
>> that the above example is simply "x++".  I don't have extensive 
>> experience with D templates and operator overloading.  It it possible to 
>> make this work transparently with all operators?  I want to support all 
>> basic types as well as structs and classes.  Could someone with more 
>> experience fill me in on the caveats involved in implementing something 
>> like this?  Has anyone else already solved this problem?  This seems like 
>> a feature that should be included in the standard library.
>>
>> -Craig
>
> Tango has tango.core.Thread.ThreadLocal for thrad-local storage. I don't 
> know about phobos, but if it's not there it should be.

Suite!  I think I've seen the term "thread local", but it never occured to 
me what it meant.  Goes to show you how green I am when it comes to 
threading.  I'll check it out.  Thanks.

-Craig 





More information about the Digitalmars-d mailing list