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

grocery_stocker cdalten at gmail.com
Fri Apr 10 09:26:47 EDT 2009


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

if __name__ == "__main__":
    #lock = thread.allocate_lock()
    lock = threading.RLock()

    counter = 0
    first = 0
    second = 0

    thread.start_new_thread(get_first_part, ("Thread1", lock, 2))
    thread.start_new_thread(get_second_part, ("Thread2", lock, 2))
    thread.start_new_thread(get_both_parts, ("Thread3", lock, 2))

    #Yes I was told this was bad, but I'm still doing until I can make
it beyond
    #the basics.
    while 1: pass

The code will jsut hang....

[cdalten at localhost oakland]$ ./rlock.py
Thread1 value is 1
Thread2 value is 2
Traceback (most recent call last):
  File "./rlock.py", line 57, in ?
    while 1: pass
KeyboardInterrupt

How come RLock isn't working in this example?



More information about the Python-list mailing list