File: critical_section.h

package info (click to toggle)
regina-normal 7.4.1-1.1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 154,244 kB
  • sloc: cpp: 295,026; xml: 9,992; sh: 1,344; python: 1,225; perl: 616; ansic: 138; makefile: 26
file content (56 lines) | stat: -rw-r--r-- 1,610 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright (c) 2016-2025 The Pybind Development Team.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#pragma once

#include "pytypes.h"

PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)

/// This does not do anything if there's a GIL. On free-threaded Python,
/// it locks an object. This uses the CPython API, which has limits
class scoped_critical_section {
public:
#ifdef Py_GIL_DISABLED
    explicit scoped_critical_section(handle obj1, handle obj2 = handle{}) {
        if (obj1) {
            if (obj2) {
                PyCriticalSection2_Begin(&section2, obj1.ptr(), obj2.ptr());
                rank = 2;
            } else {
                PyCriticalSection_Begin(&section, obj1.ptr());
                rank = 1;
            }
        } else if (obj2) {
            PyCriticalSection_Begin(&section, obj2.ptr());
            rank = 1;
        }
    }

    ~scoped_critical_section() {
        if (rank == 1) {
            PyCriticalSection_End(&section);
        } else if (rank == 2) {
            PyCriticalSection2_End(&section2);
        }
    }
#else
    explicit scoped_critical_section(handle, handle = handle{}) {};
    ~scoped_critical_section() = default;
#endif

    scoped_critical_section(const scoped_critical_section &) = delete;
    scoped_critical_section &operator=(const scoped_critical_section &) = delete;

private:
#ifdef Py_GIL_DISABLED
    int rank{0};
    union {
        PyCriticalSection section;
        PyCriticalSection2 section2;
    };
#endif
};

PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)