One more observation:
always work with local copies of anything that should not be changed externally.
I am surprised that this isn't what happens in the compiled code anyway. I.e. given your source code
v -= d;
if (v < 0) v = 0;
if (v > 180) v = 180;
f(v);
I would expect the compiler to generate code that keeps v in a register through all of that and not read and write to the global variable location, i.e. in pseudo-assmbler:
reg = load(v)
reg = reg - d
compare reg, 0
if less reg = 0
compare reg, 180
if greater reg = 180
store reg to v
move from reg to function arg location (if different)
call f
In that case, there is no opportunity for the concurrent invocation of the function to modify the value of v between the clamping tests and the subsequent use.
Maybe you have compiled with no optimisation? Maybe your real code is more complicated than what you've posted?
Anyway, I suggest that you look at the generated code (if you can work out how to do that) and see if it is really doing what you think it is doing.
Topic:
Programming Languages
SubTopic:
Swift
Tags: