From 451a9b130653e008fb78f5cd0f21e5b049abfcea Mon Sep 17 00:00:00 2001 From: Daniel Greenfeld Date: Tue, 20 May 2014 09:00:12 -0700 Subject: [PATCH] Document how to use threaded_cached_property and it's place in history --- HISTORY.rst | 3 ++- README.rst | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index 54efc9a..18d5858 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -3,9 +3,10 @@ History ------- -0.1.4 (2014-05-18) +0.1.5 (2014-05-20) ++++++++++++++++++ +* Added threading support with new `threaded_cached_property` decorator * Documented cache invalidation * Updated credits * Sourced the bottle implementation diff --git a/README.rst b/README.rst index a447a7c..78c6691 100644 --- a/README.rst +++ b/README.rst @@ -104,10 +104,51 @@ Results of cached functions can be invalidated by outside forces. Let's demonstr >>> m.boardwalk 600 -Warning -------- +Working with Threads +--------------------- + +What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which unfortunately causes problems with the standard `cached_property`. In this case, switch to using the `threaded_cached_property`: + +.. code-block:: python + + import threading + + from cached_property import cached_property + + class Monopoly(object): + + def __init__(self): + self.boardwalk_price = 500 + self.lock = threading.Lock() + + @threaded_cached_property + def boardwalk(self): + """threaded_cached_property is really nice for when no one waits + for other people to finish their turn and rudely start rolling + dice and moving their pieces.""" + + sleep(1) + # Need to guard this since += isn't atomic. + with self.lock: + self.boardwalk_price += 50 + return self.boardwalk_price + +.. code-block:: python + + >>> from threading import Thread + >>> from monopoly import Monopoly + >>> monopoly = Monopoly() + >>> threads = [] + >>> for x in range(10): + >>> thread = Thread(target=lambda: monopoly.boardwalk) + >>> thread.start() + >>> threads.append(thread) + + >>> for thread in threads: + >>> thread.join() + + >>> self.assertEqual(m.boardwalk, 550) -This library currently doesn't work with threads. Please see https://github.com/pydanny/cached-property/issues/6. Credits -------- -- 2.30.2