I can't get RLock to work (warning, the following code is pretty long)

Peter Otten __peter__ at web.de
Fri Apr 10 11:39:53 EDT 2009


grocery_stocker wrote:

> On Apr 10, 6:48 am, Peter Otten <__pete... at web.de> wrote:
>> grocery_stocker wrote:
>> > When I run the following...
>>
>> > #!/usr/bin/python
>>
>> > import time
>> > import thread
>> > import threading
>>
>> > def get_first_part(string, lock, sleeptime, *args):
>> >         global counter
>> >         lock.acquire()
>> >         try:
>> >                 counter = counter + 1
>> >                 data = counter
>> >                 print "%s value is %d" % (string, counter)
>> >                 time.sleep(sleeptime)
>> >         finally:
>> >                 lock.release()
>> >         return data
>> > def get_both_parts(string, lock, sleeptime, *args):
>> >         global first, second
>> >         lock.acquire()
>> >         try:
>> >                 first = get_first_part()
>> >                 second = get_second_part()
>> >                 print "%s values are %d and %d" % (string, first,
>> > second)
>> >                 time.sleep(sleeptime)
>> >         finally:
>> >                 lock.release()
>> >                 return first, second
>> > How come RLock isn't working in this example?
>>
>> When get_both_parts() acquires the lock it invokes get_first_part() which
>> tries to acquire the lock. This fails because get_both_parts() does not
>> release the lock until after get_first_part() has finished...
>>
>> Peter
> 
> 
> i thought a Rlock() (vs a Lock()) was suspposed to get around this
> kind of a problem.

Oops, yes. In get_both_parts() try calling get_first_part/get_second_part()
with the three necessary arguments...

Peter



More information about the Python-list mailing list