1 | #pragma once |
2 | |
3 | // RAII structs to acquire and release Python's global interpreter lock (GIL) |
4 | |
5 | #include <c10/util/Deprecated.h> |
6 | #include <torch/csrc/python_headers.h> |
7 | |
8 | // TODO: Deprecate these structs after we land this diff |
9 | // (to avoid -Werror failures) |
10 | |
11 | // Acquires the GIL on construction |
12 | struct /* C10_DEPRECATED_MESSAGE( |
13 | "Use pybind11::gil_scoped_acquire instead") */ |
14 | AutoGIL { |
15 | AutoGIL() : gstate(PyGILState_Ensure()) {} |
16 | ~AutoGIL() { |
17 | PyGILState_Release(gstate); |
18 | } |
19 | |
20 | PyGILState_STATE gstate; |
21 | }; |
22 | |
23 | // Releases the GIL on construction |
24 | struct /* C10_DEPRECATED_MESSAGE( |
25 | "Use pybind11::gil_scoped_release instead") */ |
26 | AutoNoGIL { |
27 | AutoNoGIL() : save(PyEval_SaveThread()) {} |
28 | ~AutoNoGIL() { |
29 | PyEval_RestoreThread(save); |
30 | } |
31 | |
32 | PyThreadState* save; |
33 | }; |
34 | |
35 | // Runs the function without the GIL |
36 | template <typename F> |
37 | /* C10_DEPRECATED */ inline void with_no_gil(F f) { |
38 | // TODO: The deprecation here triggers a deprecated use warning |
39 | // on some versions of compilers; need to avoid this |
40 | AutoNoGIL no_gil; |
41 | f(); |
42 | } |
43 | |