Threads and Static Data
Craig Black
craigblack2 at cox.net
Sun Dec 9 22:28:17 PST 2007
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
More information about the Digitalmars-d
mailing list