ionelmc / python-lazy-object-proxy

A fast and thorough lazy object proxy.
BSD 2-Clause "Simplified" License
247 stars 36 forks source link

add a threadsafe option #83

Open mmerickel opened 3 months ago

mmerickel commented 3 months ago

It seems lazy-object-proxy is not threadsafe. If you look at the following example you will see the doit invoked multiple times in some runs of the script. For my use-cases it needs a threadsafe version of this, as the object being created is at module-scope and threadsafe itself (re.compile). It's not a big deal in some scenarios that 2 copies are created but it's not great and quite subtle when moving to this lazy-creation versus immediate creation when refactoring to use this library. Thoughts?

from lazy_object_proxy import Proxy
import threading

x = 0

def doit():
    global x
    x += 1
    print('doing it', x)
    return x

p = Proxy(doit)

def work(obj):
    print(obj)

threading.Thread(None, target=work, args=(p,)).start()
threading.Thread(None, target=work, args=(p,)).start()

output:

loop 0
doing it 1
1
doing it 2 <-- doit invoked again for the same proxy
2

expected:

loop 0
doing 1
1
1