References across threads
Jason den Dulk
jason at fairfaxecommerce.com.au
Tue Jan 19 23:23:49 PST 2010
Hi. I have a question about threads. I have not been able to set up an
environment to test this, so I though I would simply ask.
I have a system where threads access data that rarely changes. I want to
make the data shared to avoid recreating it for each thread. However, it does
change occasionally. I want new threads to use the new data, but existing
threads to continue using the old data (graceful changeover). Here is some
sample code that I created to do this (note uses Tango style).
SomeType mainCopy; // Shared object
ThreadLocal!(SomeType) localCopy; // Thread local reference to shared object.
void someFunction()
{
synchronized
{
if (some condition)
{
mainCopy = new SomeType();
}
}
localCopy.val = mainCopy;
}
My interpretation of this code is that, after mainCopy has been created,
the thread will get a local reference to that object. Future threads will
also get a reference to that object. If a future thread changes mainCopy, any
thread whose execution is past this point will have a localCopy that continues
to reference the old object, one that will be garbage collectable once they have
all finished.
My question is - Is the above a correct interpretation? Will the code do what
I think it will do? Or is my understanding of threads and/or references
seriously lacking, in which case can someone help me out?
Regards
P.S. Is there a better way to do this?
More information about the Digitalmars-d-learn
mailing list