Answer the question
In order to leave comments, you need to log in
Unsynchronized memory access and multi-threaded race?
Hello. The program (more precisely, a well-oiled part of it) recently demonstrated a race. It was not possible to repeat it intentionally - probably a very rare glitch. In connection with this question.
A complex calculation is split across multiple processors. To speed up the work, an unsynchronized cache is used (roughly speaking, an array of doubles) with such logic.
double &x = кэш[i];<br/>
if (isnan(x)) then кэш[i]=вычислить(i);<br/>
return x;<br/>
Answer the question
In order to leave comments, you need to log in
Regarding the presented piece:
Firstly, you need to understand whether in your case double manipulation operations are atomic with a blocked bus, for this you need to know the architecture of the processor on which it all starts up and see the disassembly of the presented code.
Secondly, you need to make sure that the calculate(...) function itself is reentrant.
Thirdly, where did you get the idea that this is a race?
Based on the presented code, one can only suggest wrapping it in a double checked locking, but in general, the fact that it has not yet been wrapped indicates that the first two points have already been done (which is doubtful, because in this case it is clear that in the presented there is no race in the code), or that this code is “well debugged”.
I can advise upgrading:
double &x = cache[i];
if (isnan(x)) then
{
cache[i]=1; // so that in vain for one i many threads do not calculate(i);
cache[i]=calculate(i);
}
return x;
And about the races - what was the race? Assignment and reading are sort of like atomic operations...
If the data is not aligned, then there can be any tricks, atomicity is not guaranteed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question