Fix a data race between clear_keep_alive and state. #1191
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.
In JAX CI, we saw the following data race:
The race looks like this:
state
andclear_keep_alive
are two bitfields on the same object accessed concurrently, so this is a data race, per the C++20 standard:[intro.races] (6.9.2.1) Data races: Paragraph 21 defines a data race and its consequence: "The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other... Any such data race results in undefined behavior.". Paragraph 2 defines conflicting actions as modifying or reading/modifying the same memory location.
[intro.memory] (6.7.1) Memory model: This section precisely defines what a "memory location" is for bitfields. Paragraph 3 states: "A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having nonzero width.".
This PR splits clear_keep_alive into a separate non-bitfield member. This may or may not be a sufficient fix, in particular, one can imagine that it may be possible for multiple threads to call keep_alive concurrently, so it may need to be an atomic value.