I need to value an if condition, but I need to be careful about possible modification of a variable by other threads.
My solution is
array.each do |anything|
if (mutex.synchronize do shared_var <= my_var end)
next
end
end
It seems to work. But what is exactly the if statement checking? And how about this other code?
array.each do |anything|
mutex.synchronize do
if shared_var <= my_var
next
end
end
end
Are they equivalent? Does the inner next do its job even if it is included in a mutex? And why?
Just look at the structure, I showed only the part of the program relevant for my question.
synchronizereturns whatever the block passed to it returns, so theifstatement is ultimately checkingshared_var <= my_var.I think it’s self-explanatory what the
ifstatement here is checking, and it is the same as above.No.
No, and this is why they are not equivalent. When
nextis called inside the block of thesynchronizecall, it isnexting in that block (not theforeach), which is equivalent toreturnhere since there’s no “next”. When it’s outside that block, it’snexting over the actual outer block (foreach) you expect.Thus, you likely want the first code block.