Skip to content

Commit 0d03a18

Browse files
committed
gh-150902: Optimize PyCriticalSection2 to skip locking the same locks as the ones held by the current CS2
1 parent f051c68 commit 0d03a18

1 file changed

Lines changed: 15 additions & 0 deletions

File tree

Python/critical_section.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,21 @@ _PyCriticalSection2_BeginSlow(PyThreadState *tstate, PyCriticalSection2 *c, PyMu
7272
c->_cs_base._cs_prev = 0;
7373
return;
7474
}
75+
// Same optimization as in _PyCriticalSection_BeginSlow: skip locking when
76+
// recursively acquiring the same locks.
77+
if (tstate->critical_section &&
78+
tstate->critical_section & _Py_CRITICAL_SECTION_TWO_MUTEXES) {
79+
PyCriticalSection2 *prev2 = (PyCriticalSection2 *)
80+
untag_critical_section(tstate->critical_section);
81+
assert(m1 < m2);
82+
assert(prev2->_cs_base._cs_mutex < prev2->_cs_mutex2);
83+
if (prev2->_cs_base._cs_mutex == m1 && prev2->_cs_mutex2 == m2) {
84+
c->_cs_base._cs_mutex = NULL;
85+
c->_cs_mutex2 = NULL;
86+
c->_cs_base._cs_prev = 0;
87+
return;
88+
}
89+
}
7590
c->_cs_base._cs_mutex = NULL;
7691
c->_cs_mutex2 = NULL;
7792
c->_cs_base._cs_prev = tstate->critical_section;

0 commit comments

Comments
 (0)