[Tutor] Locking a specific variable

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Apr 24 07:41:15 CEST 2006



On Sun, 23 Apr 2006, Tino Dai wrote:

>     I am wondering if you could lock a specific variable with thread 
> locking. Let me illustrate:
>
> def ftpQueuePut(filename="")::
>  if len(filename) > 0:
>      try:
>           fileQueue.put(filename,True,1)    #Variable that I would like to
> lock
>      except Queue.full:
>           print "Queue is full"
>   else:
>           pass
>
> def ftpQueueGet():
>     try:
>          filename=fileQueue.get(True,1)  #Variable that I would like to
> lock
>          return filename
>     except Queue.Empty:
>          pass

Hi Tino,

I'm not quite sure I get it, but ok.  *grin* I'll assume that fileQueue is 
an instance of the Queue class:

     http://www.python.org/doc/lib/module-Queue.html

If so: why not allow fileQueue to grow unbounded?


> Presently, the only way that I can see to do this using Python is to 
> combine the two functions into one and lock and unlock the entire thing 
> . That doesn't seem efficient and/or elegant to me. Any pointers about 
> this?

Do you know about the thread-locking primitives?  There are a few kinds 
provided by Python's threading module:

     http://www.python.org/doc/lib/module-threading.html

Are you already familiar with the concept of a RLock or a Lock?


More information about the Tutor mailing list