PyString, &str and Python::allow_threads #4844
Replies: 1 comment 1 reply
-
There are ways to modify strings via the C API. So much code assumes that strings are immutable after being created though that any C code actually mutating a string is certainly thread-unsafe in a way that should be considered a bug IMO.
Yup, that's exactly right. And you know that the reference count has to be at least one because of the |
Beta Was this translation helpful? Give feedback.
-
I'm adding a new concurrency chapter to our Rust-Python interoperability workshop and I ended up writing something equivalent to what follows:
I want to check my understanding of what's happening (and if that's correct).
text.to_str()
gives us a view over data that's still owned by the Python runtime, and thus GIL-constrained. Intuitively, that should translate into the view type beingUngil
.At the same time, though, strings are immutable in Python (are they?). Therefore, it's fine to read the string data as long as we are sure it hasn't been garbage collected.
Since the closure in
py.allow_threads
executes to completion beforeword_count
returns, we know for sure that the reference counter for the string behindtext
is at least one, therefore it won't be garbage collected and we can sleep safe and sound.Does that check out?
Beta Was this translation helpful? Give feedback.
All reactions