coady / multimethod

Multiple argument dispatching.
https://coady.github.io/multimethod
Other
284 stars 23 forks source link

Issues with thread safety #73

Closed maxme1 closed 1 year ago

maxme1 commented 1 year ago

Hi!

I am occasionally having a race condition while using multimethod-decorated functions in different threads:

  File "/path/to/env/multimethod/__init__.py", line 313, in __call__
    func = self[tuple(func(arg) for func, arg in zip(self.type_checkers, args))]
  File "/path/to/env/multimethod/__init__.py", line 299, in __missing__
    for key in self.parents(types):
  File "/path/to/env/multimethod/__init__.py", line 248, in parents
    parents = {key for key in self if isinstance(key, signature) and key < types}
  File "/path/to/env/multimethod/__init__.py", line 248, in <setcomp>
    parents = {key for key in self if isinstance(key, signature) and key < types}
RuntimeError: dictionary changed size during iteration

I didn't manage to figure out the conditions in which it occurs, but in my code it happens in around 0.5% of runs. Maybe you could protect the types -> function mapping with a RLock?