Simple thread-safe counter?

Aahz aahz at pythoncraft.com
Sat Apr 2 12:59:36 EST 2005


In article <mailman.1224.1112418208.1799.python-list at python.org>,
Skip Montanaro  <skip at pobox.com> wrote:
>
>Obviously, if you want multiple counters for some reason a little
>information hiding with a class would help (also untested):
>
>    import Queue
>
>    class Counter:
>        def __init__(self, start=0):
>            self.counter = Queue.Queue()
>            self.counter.put(start)
>
>        def __call__(self):
>            i = self.counter.get()
>            self.counter.put(i+1)
>            return i

This is one case where'd recommend using a plan RLock() instead of using
Queue -- the RLock() will be more efficient:

import threading

class Counter:
    def __init__(self, start=0, increment=1):
        self.counter = start
        self.increment = increment
        self.lock = threading.RLock()
    def __call__(self):
        self.lock.acquire()
        self.counter += self.increment
        i = self.counter
        self.lock.release()
        return i

There are several tricks one can use to squeeze further efficiency gains
from this, including using Lock() instead of RLock().
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code -- 
not in reams of trivial code that bores the reader to death."  --GvR



More information about the Python-list mailing list