]>
git.proxmox.com Git - ceph.git/blob - ceph/src/mgr/Gil.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 * Ceph - scalable distributed file system
6 * Copyright (C) 2017 SUSE LLC
8 * This is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License version 2.1, as published by the Free Software
11 * Foundation. See file COPYING.
21 typedef struct _ts PyThreadState
;
27 * Wrap PyThreadState to carry a record of which POSIX thread
28 * the thread state relates to. This allows the Gil class to
29 * validate that we're being used from the right thread.
34 explicit SafeThreadState(PyThreadState
*ts_
);
37 : ts(nullptr), thread(0)
44 void set(PyThreadState
*ts_
)
47 thread
= pthread_self();
52 // Use one of these in any scope in which you need to hold Python's
53 // Global Interpreter Lock.
55 // Do *not* nest these, as a second GIL acquire will deadlock (see
56 // https://docs.python.org/2/c-api/init.html#c.PyEval_RestoreThread)
58 // If in doubt, explicitly put a scope around the block of code you
59 // know you need the GIL in.
61 // See the comment in Gil::Gil for when to set new_thread == true
65 Gil(const Gil
&) = delete;
66 Gil
& operator=(const Gil
&) = delete;
68 Gil(SafeThreadState
&ts
, bool new_thread
= false);
72 SafeThreadState
&pThreadState
;
73 PyThreadState
*pNewThreadState
= nullptr;
76 // because the Python runtime could relinquish the GIL when performing GC
77 // and re-acquire it afterwards, we should enforce following locking policy:
78 // 1. do not acquire locks when holding the GIL, use a without_gil or
79 // without_gil_t to guard the code which acquires non-gil locks.
80 // 2. always hold a GIL when calling python functions, for example, when
81 // constructing a PyFormatter instance.
83 // a wrapper that provides a convenient RAII-style mechinary for acquiring
84 // and releasing GIL, like the macros of Py_BEGIN_ALLOW_THREADS and
85 // Py_END_ALLOW_THREADS.
86 struct without_gil_t
{
92 PyThreadState
*save
= nullptr;
93 friend struct with_gil_t
;
97 with_gil_t(without_gil_t
& allow_threads
);
100 without_gil_t
& allow_threads
;
103 // invoke func with GIL acquired
104 template<typename Func
>
105 auto with_gil(without_gil_t
& no_gil
, Func
&& func
) {
106 with_gil_t gil
{no_gil
};
107 return std::invoke(std::forward
<Func
>(func
));
110 template<typename Func
>
111 auto without_gil(Func
&& func
) {
112 without_gil_t no_gil
;
113 return std::invoke(std::forward
<Func
>(func
));