Many Python libraries strictly specify that, for example, some functionality is not thread-safe. Here is one example pypi cachetools
The authors write - Note Please be aware that all these classes are not thread-safe. Access to a shared cache from multiple threads must be properly synchronized, e.g. by using one of the memoizing decorators with a suitable lock object.
Hence the question. After removing the GIL from python3.13 and adding mutexes, are all programs now thread-safe by default and do not need synchronization? This also applies to the asyncio module and all the others that also have many warnings about thread-unsafety in multithreaded applications.
Then why would all the locks (Lock, RLock, and so on) be needed in the threading module?
No, those mutexes have no effect on these situations. The primary effect of the mutexes is that individual python objects don’t get corrupted on a C level if multiple threads access them.
However, for e.g. cachetools that doesn’t mean the python code is synced up in the correct way. Multiple threads might still both see the value missing and start calculating.
I had a look at PEP 703 and it’s unclear to me which operations are now thread safe and which are not.
E.g. is assigning to a dict thread-safe, or do I need to hold a Lock?
from threading import Thread
class Foo:
def _t(self, name):
self._d[name] = name + name
def run(self):
self._d = {}
threads = [Thread(target=self._t, args=(name,))
for name in ["foo", "bar", "baz"]]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(self._d)
Foo().run()
That could mean at least two things:
Above code works as expected, i.e. the program will print {'foo': 'foofoo', 'bar': 'barbar', 'baz': 'bazbaz'} (possibly in different order).
The program doesn’t crash but might print something else, e.g. fewer keys.