ACloudViewer  3.9.4
A Modern Library for 3D Data Processing
Threading.h
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // - CloudViewer: www.cloudViewer.org -
3 // ----------------------------------------------------------------------------
4 // Copyright (c) 2018-2024 www.cloudViewer.org
5 // SPDX-License-Identifier: MIT
6 // ----------------------------------------------------------------------------
7 
8 #pragma once
9 
10 #include <QException>
11 
12 #include <pybind11/pybind11.h>
13 
14 namespace py = pybind11;
15 
17 {
18  public:
19  explicit PyThreadStateGuard(PyInterpreterState *interpState)
20  {
21  pCurrentState = PyThreadState_New(interpState);
22  PyEval_AcquireThread(pCurrentState);
23  }
24 
26  {
27  PyThreadState_Clear(pCurrentState);
28  PyEval_ReleaseThread(pCurrentState);
29 
30  PyThreadState_Delete(pCurrentState);
31  }
32 
33  private:
34  PyThreadState *pCurrentState{nullptr};
35 };
36 
38 {
39  explicit PyThreadStateReleaser() : state(PyEval_SaveThread()) {}
40 
42  {
43  PyEval_RestoreThread(state);
44  }
45 
46  PyThreadState *state{nullptr};
47 };
48 
49 class ThreadException : public QException
50 {
51  public:
52  explicit ThreadException(const std::exception &err) : e(err) {}
53 
54  void raise() const override
55  {
56  throw *this;
57  }
58 
59  QException *clone() const override
60  {
61  return new ThreadException(*this);
62  }
63 
64  const char *what() const noexcept override
65  {
66  return e.what();
67  }
68 
69  std::exception error() const
70  {
71  return e;
72  }
73 
74  private:
75  std::exception e;
76 };
77 
78 inline py::object
79 call_fn(PyThreadState *main_state, py::object callable, py::args args, py::kwargs kwargs)
80 {
81  PyThreadStateGuard threadStateGuard{main_state->interp};
82  try
83  {
84  return callable(*args, **kwargs);
85  }
86  catch (const std::exception &e)
87  {
88  throw ThreadException(e);
89  }
90 }
py::object call_fn(PyThreadState *main_state, py::object callable, py::args args, py::kwargs kwargs)
Definition: Threading.h:79
virtual ~PyThreadStateGuard()
Definition: Threading.h:25
PyThreadStateGuard(PyInterpreterState *interpState)
Definition: Threading.h:19
std::exception error() const
Definition: Threading.h:69
const char * what() const noexcept override
Definition: Threading.h:64
QException * clone() const override
Definition: Threading.h:59
ThreadException(const std::exception &err)
Definition: Threading.h:52
virtual ~PyThreadStateReleaser()
Definition: Threading.h:41
PyThreadState * state
Definition: Threading.h:46