gil_simple.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright (c) 2016-2025 The Pybind Development Team.
  2. // All rights reserved. Use of this source code is governed by a
  3. // BSD-style license that can be found in the LICENSE file.
  4. #pragma once
  5. #include "detail/common.h"
  6. #include <cassert>
  7. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  8. class gil_scoped_acquire_simple {
  9. PyGILState_STATE state;
  10. public:
  11. gil_scoped_acquire_simple() : state{PyGILState_Ensure()} {}
  12. gil_scoped_acquire_simple(const gil_scoped_acquire_simple &) = delete;
  13. gil_scoped_acquire_simple &operator=(const gil_scoped_acquire_simple &) = delete;
  14. ~gil_scoped_acquire_simple() { PyGILState_Release(state); }
  15. };
  16. class gil_scoped_release_simple {
  17. PyThreadState *state;
  18. public:
  19. // PRECONDITION: The GIL must be held when this constructor is called.
  20. gil_scoped_release_simple() {
  21. assert(PyGILState_Check());
  22. state = PyEval_SaveThread();
  23. }
  24. gil_scoped_release_simple(const gil_scoped_release_simple &) = delete;
  25. gil_scoped_release_simple &operator=(const gil_scoped_release_simple &) = delete;
  26. ~gil_scoped_release_simple() { PyEval_RestoreThread(state); }
  27. };
  28. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)