gh-120496: Make enum_iter thread safe #120591
Open
+53
−5
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.
We make
enum_iter
thread-safe using a critical section. We use the same approach as in #119438 to allow for exits in the middle of the critical section. The methodenum_iter_long
is guarded by the critical section fromenum_long
.Without making
enum_iter
thread safe problems can occur:enumerate(range(10))
pairs(n, m)
withn
unqual tom
can be generatedsys.maxsize
, e.g.enumerate(range(sys.maxsize - 10, sys.maxsize + 10))
an overflow can occur.enum_iter
keeps track of the returned tuple. In the free-threaded build multiple threads can operate on the same tuple.To determine the overhead of making enumerate thread-safe here are some benchmarking results for a single-threaded application. Performance when actually using multiple-threads to readout the enumerate is considered less important.
Benchmark script:
Results of main versus free-threading:
Results of free-threading vs. free-threading with this PR:
The case
enumerate(range10)
is not affected by the PR (used to check the benchmarking is stable). The caseslist(enumerate(range(x)))
slow down a bit. More representative is perhaps theweighted_sum
benchmark where the enumerate is used a for loop with a minimal amount of work. There the overhead of the locking not significant.