Wednesday, 10 February 2021

Why reversed() removes thread safety?

A common idiom in CPython to ensure thread safety for iteration is using tuple().

For example - tuple(dict.items()) is guaranteed to be threadsafe in CPython even if items are removed by a different thread.

This is because the interpreter does not run the eval loop and does not release the GIL while running these C functions. I've tested it, and it works great.

However, tuple(reversed(dict.items())) doesn't seem to be threadsafe, and I can't understand why. It's not running any Python function, it isn't explicitly releasing the GIL. Why am I still getting errors if I delete keys from the dict while it runs on a different thread?



from Why reversed() removes thread safety?

No comments:

Post a Comment