[Tutor] Locking a specific variable (fwd)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Apr 24 19:51:14 CEST 2006



---------- Forwarded message ----------
Date: Mon, 24 Apr 2006 07:32:04 -0400
From: Tino Dai <tinoloc at gmail.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Locking a specific variable

Hey there Danny,

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?
>


Yup, I'm familiar with those. In all of the examples, I have seen, the
critical region happens in one specific area eg a part of a function with a
lock and release around it. My question is there a way to lock a specific
variable so that even though other functions are attempting to access it,
they will not until the first function has released it. Examples below

# This example shows the way I have seen it in python tutorials
def function1():
      blah blah
      function3()
      blah blah

def function2():
      blah blah
      function3()
      blah blah

def function3():
     acquire lock
     does some stuff
     release lock

t = Thread.thread()
t.start(function1())
t.start(function2())

# The way I would like to do it, so we have two different instances of the
same variable, and only # one function can access it at a time. If a
function comes to that variable and finds a lock on it, # it will wait until
the lock is released.  And the variable happens to be a queue
def function1():
      blah blah
      acquire lock of variable only so that only function1 can access this at
a given time
      ....increment some variable.....
          release the function2 lock on this variable
      blah blah

def function2():
      blah blah
      acquire lock of variable only so that only function2 can access this at
a given time
      ....decrement some variable......
      release the function2 lock on this variable
      blah blah

t = Thread.thread()
t.start(function1())
t.start(function2())


Does that make more sense?


TIA,
Tino


More information about the Tutor mailing list