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

Peter Otten __peter__ at web.de
Fri Apr 10 09:48:45 EDT 2009


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



More information about the Python-list mailing list