Caffe2 - C++ API
A deep learning, cross platform ML framework
auto_gil.h
1 #pragma once
2 
3 // RAII structs to acquire and release Python's global interpreter lock (GIL)
4 
5 #include <torch/csrc/python_headers.h>
6 
7 // Acquires the GIL on construction
8 struct AutoGIL {
9  AutoGIL() : gstate(PyGILState_Ensure()) {
10  }
11  ~AutoGIL() {
12  PyGILState_Release(gstate);
13  }
14 
15  PyGILState_STATE gstate;
16 };
17 
18 // Releases the GIL on construction
19 struct AutoNoGIL {
20  AutoNoGIL() : save(PyEval_SaveThread()) {
21  }
22  ~AutoNoGIL() {
23  PyEval_RestoreThread(save);
24  }
25 
26  PyThreadState* save;
27 };
28 
29 // Runs the function without the GIL
30 template<typename F>
31 inline void with_no_gil(F f) {
32  AutoNoGIL no_gil;
33  f();
34 }