Simple thread-safe counter?

Neil Benn neil.benn at arcor.de
Sat Apr 2 06:08:25 EST 2005


Paul Rubin wrote:

>Skip Montanaro <skip at pobox.com> writes:
>  
>
>>How about (untested):
>>
>>    import Queue
>>    counter = Queue.Queue()
>>    counter.put(0)
>>    def f():
>>        i = counter.get()
>>        counter.put(i+1)
>>        return i
>>    
>>
>
>Hmmm, that's a bit messier than I hoped for, but it looks sure to work.
>
>I think for my immediate requirement, I'm going to use xrange as Tim
>suggested.  However, I can't be sure that will work in non-GIL
>implementations.
>  
>
Hello,

          Simple xrange stuff won't work in Jython as Sython is running 
on a JVM which doesn't have a GIL kinda thing.  If you wanna return a 
sequential number then you'll need something like :

<PSEUDO CODE>

class COUNTER:
    DOC : THIS WILL RETURN AN INCRMENTING LIST OF NUMBERS - THREAD SAFE.

    FUNCTION INIT:
      OBJRLOCK= RLOCK()
      INTRETURNNUM = 0

    FUNCTION NEXT
        TRY{
            RLOCK.AQUIRE
        }FINALLY{
           RLOCK.RELEASE
        }

</PSUEDO CODE>

    That basically all you'll need, if you make it iteratable of 
whatever - you need to wrap the business end of what you are doing 
around a recursive lock.  Personally I dislike the GIL so I avoid 
writing code that takes advantages of it.

    Why psuedo code - this is similar to python code I know but it means 
I'm not posting untested python code!!

Cheers,

Neil



More information about the Python-list mailing list