Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Tinche
Created May 19, 2014 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tinche/e092adeb8171fd0843dd to your computer and use it in GitHub Desktop.
Save Tinche/e092adeb8171fd0843dd to your computer and use it in GitHub Desktop.
"""Cached property multithreading test."""
from threading import Lock, Thread
from time import sleep
from cached_property import cached_property
COUNT = 0
COUNT_LOCK = Lock()
NUM_THREADS = 10
class Test(object):
def __init__(self, val):
self._val = val
@cached_property
def val(self):
"""Val getter."""
sleep(1)
global COUNT_LOCK, COUNT
with COUNT_LOCK:
COUNT = COUNT + 1
return self._val
t = Test(5)
threads = []
for _ in range(NUM_THREADS):
thread = Thread(target=lambda: t.val)
thread.start()
threads.append(thread)
for t in threads:
t.join()
print "Cached method called", COUNT, "times"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment