Make MuJoCo Python bindings compatible with free-threading.
Introduce a new header `gil.h` defining `MutexLockIfGilDisabled` to support thread-safety in both standard and free-threaded CPython builds. Protect critical shared states and registries: - Guard global Python callback pointers in `callbacks.cc` using a mutex. Move `gil_scoped_acquire` into local blocks around refcount modifications to prevent `longjmp` from bypassing destructors. - Protect raw pointer maps in `structs_wrappers.cc` with static mutexes. - Replace TOCTOU race in `mjcb_time` initialization with thread-safe `std::call_once`. - Add synchronization to lazy indexer array cache initialization in `indexers.cc` and `indexer_xmacro.h`. - Protect vector mutations in `StructListBase::PopulateUpTo` in `structs.h` with a mutex. - Revert unnecessary atomic changes to threadpool counters. - Declare free-threading compatibility by passing `pybind11::mod_gil_not_used()` to all extension modules. Fixes #3259 Fixes #3256 Fixes #2978 PiperOrigin-RevId: 941101502 Change-Id: Iec4ce58afcbc75d4b0be6a9a21fc8a47854242e3
This commit is contained in:
committed by
Copybara-Service
parent
cab191755a
commit
a07ae6f849
@@ -15,6 +15,7 @@
|
||||
#ifndef MUJOCO_PYTHON_INDEXERS_H_
|
||||
#define MUJOCO_PYTHON_INDEXERS_H_
|
||||
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
@@ -104,6 +105,7 @@ class MjModelGroupedViewsBase {
|
||||
std::string name_;
|
||||
raw::MjModel* m_;
|
||||
pybind11::handle owner_;
|
||||
mutable std::mutex lazy_init_mutex_;
|
||||
};
|
||||
|
||||
#define XGROUP(MjModelGroupedViews, field, nfield, FIELD_XMACROS) \
|
||||
@@ -142,6 +144,7 @@ class MjModelIndexer {
|
||||
pybind11::handle owner_;
|
||||
NameToIDMappings name_to_id_;
|
||||
IDToNameMappings id_to_name_;
|
||||
mutable std::mutex lazy_init_mutex_;
|
||||
|
||||
// Lazily instantiate a grouped views object when accessed from Python, but
|
||||
// cache it once made so that we can return the same one if requested again.
|
||||
@@ -172,6 +175,7 @@ class MjDataGroupedViewsBase {
|
||||
raw::MjData* d_;
|
||||
const raw::MjModel* m_;
|
||||
pybind11::handle owner_;
|
||||
mutable std::mutex lazy_init_mutex_;
|
||||
};
|
||||
|
||||
#define XGROUP(MjDataGroupedViews, field, nfield, FIELD_XMACROS) \
|
||||
@@ -212,6 +216,7 @@ class MjDataIndexer {
|
||||
pybind11::handle owner_;
|
||||
NameToIDMappings name_to_id_;
|
||||
IDToNameMappings id_to_name_;
|
||||
mutable std::mutex lazy_init_mutex_;
|
||||
|
||||
// Lazily instantiate a grouped views object when accessed from Python, but
|
||||
// cache it once made so that we can return the same one if requested again.
|
||||
|
||||
Reference in New Issue
Block a user