-
Notifications
You must be signed in to change notification settings - Fork 217
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix race condition in free-threaded Python (fixes issue #867)
This commit addresses an issue arising when multiple threads want to access the Python object associated with the same C++ instance, which does not exist yet and therefore must be created. @vfdev-5 reported that TSAN detects a race condition in code that uses this pattern, caused by concurrent unprotected reads/writes of internal ``nb_inst`` fields. There is also a larger problem: depending on how operations are sequenced, it is possible that two threads simultaneously create a Python wrapper, which violates the usual invariant that each (C++ instance pointer, type) pair maps to at most one Python object. This PR updates nanobind to preserve this invariant. When registering a newly created wrapper object in the internal data structures, nanobind checks if another equivalent wrapper has been created in the meantime. If so, we destroy the thread's instance and return the registered one. This requires some extra handling code, that, however, only runs with very low probability. It also adds a new ``registered`` bit flag to ``nb_inst``, which makes it possible to have ``nb_inst`` objects that aren't registered in the internal data structures. I am planning to use that feature to fix the (unrelated) issue #879.
- Loading branch information
Showing
3 changed files
with
66 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters