Skip to content

Commit 032fef2

Browse files
committed
chore: handle null for py::scoped_critical_section
1 parent 33fb533 commit 032fef2

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

include/pybind11/critical_section.h

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,27 @@ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
1313
class scoped_critical_section {
1414
public:
1515
#ifdef Py_GIL_DISABLED
16-
explicit scoped_critical_section(handle obj) : has2(false) {
17-
PyCriticalSection_Begin(&section, obj.ptr());
16+
scoped_critical_section(handle obj1, handle obj2) : m_ptr1(obj1.ptr()), m_ptr2(obj2.ptr()) {
17+
if (m_ptr1 == nullptr) {
18+
std::swap(m_ptr1, m_ptr2);
19+
}
20+
if (m_ptr2 != nullptr) {
21+
PyCriticalSection2_Begin(&section2, m_ptr1, m_ptr2);
22+
} else if (m_ptr1 != nullptr) {
23+
PyCriticalSection_Begin(&section, m_ptr1);
24+
}
1825
}
1926

20-
scoped_critical_section(handle obj1, handle obj2) : has2(true) {
21-
PyCriticalSection2_Begin(&section2, obj1.ptr(), obj2.ptr());
27+
explicit scoped_critical_section(handle obj) : m_ptr1(obj.ptr()) {
28+
if (m_ptr1 != nullptr) {
29+
PyCriticalSection_Begin(&section, m_ptr1);
30+
}
2231
}
2332

2433
~scoped_critical_section() {
25-
if (has2) {
34+
if (m_ptr2 != nullptr) {
2635
PyCriticalSection2_End(&section2);
27-
} else {
36+
} else if (m_ptr1 != nullptr) {
2837
PyCriticalSection_End(&section);
2938
}
3039
}
@@ -39,7 +48,8 @@ class scoped_critical_section {
3948

4049
private:
4150
#ifdef Py_GIL_DISABLED
42-
bool has2;
51+
PyObject *m_ptr1{nullptr};
52+
PyObject *m_ptr2{nullptr};
4353
union {
4454
PyCriticalSection section;
4555
PyCriticalSection2 section2;

0 commit comments

Comments
 (0)