8000 gh-135871: Fix needless spinning in _PyMutex_LockTimed (timeout==0) by jtibbertsma · Pull Request #135872 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-135871: Fix needless spinning in _PyMutex_LockTimed (timeout==0) #135872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 25, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
gh-135871: Fix needless spinning in _PyMutex_LockTimed (timeout==0)
* Move the timeout == 0 guard outside the else so a non-blocking call
  returns immediately after a failed CAS instead of entering the spin loop.
* Reload v on every spin iteration, allowing timed/blocking callers to
  notice an unlock promptly.

No-GIL builds now honor the semantics of non-blocking attempts and avoid
wasted CPU; GIL builds are unaffected (MAX_SPIN_COUNT == 0).
  • Loading branch information
jtibbertsma committed Jun 24, 2025
commit 7296a7d133c078f1b9d6294f64dc653c9b03eb56
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
gh-135871: _PyMutex_LockTimed() no longer spins or fails for timeout==0 in no-GIL builds; spin loop now reloads lock state.
8000
3 changes: 2 additions & 1 deletion Python/lock.c
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
return PY_LOCK_ACQUIRED;
}
}
else if (timeout == 0) {
if (timeout == 0) {
return PY_LOCK_FAILURE;
}

Expand Down Expand Up @@ -89,6 +89,7 @@ _PyMutex_LockTimed(PyMutex *m, PyTime_t timeout, _PyLockFlags flags)
// Spin for a bit.
_Py_yield();
spin_count++;
v = _Py_atomic_load_uint8_relaxed(&m->_bits);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like it fixes a logic bug but it also hurts performance

See Tools/lockbench/lockbench.py

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the review! I'm convinced, this line reduces throughput on my machine by something like 40% for 8 threads. I think changing else if to if still makes sense though. I updated the PR.

continue;
}

Expand Down
Loading
0