[Tutor] Locking a specific variable (fwd)
Kent Johnson
kent37 at tds.net
Tue Apr 25 00:25:57 CEST 2006
> 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())
What is wrong with doing exactly this?
>
> # 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
I don't understand what you mean by "two different instances of the same
variable." Can you give an example?
> 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
Do you know that Queues are already thread safe? They use locks
internally and are intended for multi-threaded use. You shouldn't have
to use any additional locks to use 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())
This code is the same as the first version except function3() has been
inlined. I don't see the benefit of this style, it just causes code
duplication.
Kent
More information about the Tutor
mailing list