|
| 1 | +// Copyright (c) 2016-2025 The Pybind Development Team. |
| 2 | +// All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include "pytypes.h" |
| 8 | + |
| 9 | +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) |
| 10 | + |
| 11 | +/// This does not do anything if there's a GIL. On free-threaded Python, |
| 12 | +/// it locks an object. This uses the CPython API, which has limits |
| 13 | +class scoped_critical_section { |
| 14 | +public: |
| 15 | +#ifdef Py_GIL_DISABLED |
| 16 | + explicit scoped_critical_section(handle obj) : has2(false) { |
| 17 | + PyCriticalSection_Begin(§ion, obj.ptr()); |
| 18 | + } |
| 19 | + |
| 20 | + scoped_critical_section(handle obj1, handle obj2) : has2(true) { |
| 21 | + PyCriticalSection2_Begin(§ion2, obj1.ptr(), obj2.ptr()); |
| 22 | + } |
| 23 | + |
| 24 | + ~scoped_critical_section() { |
| 25 | + if(has2) { |
| 26 | + PyCriticalSection2_End(§ion2); |
| 27 | + } else { |
| 28 | + PyCriticalSection_End(§ion); |
| 29 | + } |
| 30 | + } |
| 31 | +#else |
| 32 | + explicit scoped_critical_section(handle _obj) = default; |
| 33 | + scoped_critical_section(handle _obj1, handle _obj2) = default; |
| 34 | + ~scoped_critical_section() = default; |
| 35 | +#endif |
| 36 | + |
| 37 | + scoped_critical_section(const scoped_critical_section &) = delete; |
| 38 | + scoped_critical_section &operator=(const scoped_critical_section &) = delete; |
| 39 | + |
| 40 | +private: |
| 41 | +#ifdef Py_GIL_DISABLED |
| 42 | + bool has2; |
| 43 | + union { |
| 44 | + PyCriticalSection section; |
| 45 | + PyCriticalSection2 section2; |
| 46 | + }; |
| 47 | +#endif |
| 48 | +}; |
| 49 | + |
| 50 | +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) |
0 commit comments