fix:Race condition on instance variable assignment #1154
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR fixes most recent CI timeouts, specially the ones seen for JRuby:
These timeouts happen because probing
worker.run_loop?
can have the non-thread-safe side-effect of setting@run_loop = false
:If the check for
instance_variable_defined?(:@run_async)
is executed then the Ruby VM context switches to:which sets it to true:
@run_loop = true
.Then context switches back and executes the assignment part of:
@run_async
will be set tofalse
prematurely, effectively terminating the worker.One alternative solution to the changes in this PR is to wrap
#run_async?
in a mutex, but this is not necessary, as the changes introduced here respect strict Happened-before semantics: we wait untilinstance_variable_defined?(:@run_async)
returnstrue
for us to ever evaluate@run_async
, and assigning a value to@run_async
is guaranteed to happen beforeinstance_variable_defined?(:@run_async)
returnstrue
, so we now only read it when it's guaranteed to be available.Also we stop assigning a value
@run_async
, which means this method does not have to worry about read/write race conditions that it could cause.I've applied this fix to all instances of such pattern I could find in our code base.