gil_simple.h 1.4 KB

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