Skip to content

Commit 21bd43c

Browse files
committed
gh-144586: Improve _Py_yield to improve light weight cpu instruction
1 parent e682141 commit 21bd43c

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

Include/internal/pycore_lock.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ PyMutex_LockFlags(PyMutex *m, _PyLockFlags flags)
7070
// error messages) otherwise returns 0.
7171
extern int _PyMutex_TryUnlock(PyMutex *m);
7272

73-
// Yield the processor to other threads (e.g., sched_yield).
73+
// Yield the processor using a lightweight CPU pause hint (e.g., x86 PAUSE,
74+
// AArch64 WFE). Falls back to sched_yield()/SwitchToThread() on platforms
75+
// without a known pause instruction.
7476
extern void _Py_yield(void);
7577

7678

Python/lock.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,19 @@ struct mutex_entry {
4343
void
4444
_Py_yield(void)
4545
{
46-
#ifdef MS_WINDOWS
46+
#if defined(__GNUC__) || defined(__clang__)
47+
# if defined(__x86_64__) || defined(__i386__)
48+
__asm__ volatile ("pause" ::: "memory");
49+
# elif defined(__aarch64__)
50+
__asm__ volatile ("wfe");
51+
# elif defined(__arm__) && __ARM_ARCH >= 7
52+
__asm__ volatile ("yield" ::: "memory");
53+
# elif defined(__powerpc__) || defined(__ppc__) || defined(__PPC__)
54+
__asm__ volatile ("or 27,27,27" ::: "memory");
55+
# else
56+
sched_yield();
57+
# endif
58+
#elif defined(MS_WINDOWS)
4759
SwitchToThread();
4860
#elif defined(HAVE_SCHED_H)
4961
sched_yield();

0 commit comments

Comments
 (0)