Re: Arrays and thread safety
Posted by
Michael Doube on
May 07, 2009; 9:39pm
URL: http://imagej.273.s1.nabble.com/Arrays-and-thread-safety-tp3692620p3692630.html
> I don't understand all of your code, but you may have a problem like
> the following:
> Assume, e.g., running code like your replaceLabel in multiple threads:
> for (int i = start; i < end; i++) {
> if (tagArray[i] == m) {
> tagArray[i] = n;
> }
> }
> Results will be unpredictable if the ranges from 'start' to 'end'
> overlap and one thread would change tags from m=3 to n=4 and the
> other m=4 to n=5.
Exactly; ranges shouldn't overlap as each thread is given a discrete
range of array indices. Array values should be read and written only
once by only one thread each time a new ReplaceLabelThread is created.
> A side-remark: all your
> return particleLabels;
> statements look strange. particleLabels is an array. If a method
> writes to an array, its contents are modified, whether you return it
> or not. By returning it, you return the reference to the array, which
> makes sense only if you replace the array by a new one (but that
> would not be multithread-complient at all).
OK, thanks for the tip, I shall make the affected methods return void.
>
> Hope this helps,
very much,
Thanks
Mike