Creating a thread-local duplicate of a globally shared array
Andrej Mitrovic
andrej.mitrovich at gmail.com
Thu Jun 30 22:14:26 PDT 2011
I have two functions running concurrently and they share data via a
globally shared array.
Generally one thread modifies an array and potentially changes its
length, the other thread reads from it. I have to avoid too many locks
and message passing wouldn't really work since I need fast access to
the array.
I can't use the array directly in the reading thread because the array
could possibly be reallocated by the writing thread (e.g. if it
changes the .length property), while at the same time the reading
thread could just have sent the .ptr value of that array to some API
function. I've had this problem occur and the app would crash due to a
reallocation while the API was reading the array.
Here's the gist of it:
__gshared int[] values;
void foo()
{
// modify, write to the array, and possibly change the length
}
void bar()
{
// send the .ptr field of 'values' and its length to an API
function which reads
// 'values' in sequence and does some visual output.
}
Is it possible to lock 'values', but only once in the bar function
while creating a thread-local copy?
I mean something like this:
void bar()
{
static int[] localValues;
localValues = LOCK(values[]); // temporarily lock values and copy
its contents to a thread-local array
// values is now unlocked and foo() can modify/write to it again
APIFun(localValues.ptr, localValues.length); // safe to pass this
array to the API
}
More information about the Digitalmars-d-learn
mailing list