Python:使用具有多个线程的RLock

时间:2014-07-08 15:29:16

标签: python

预期的输出应该是所有3个func()过程完成和完成的#39;不打印,而是test()在func()中第一次打印(i)后返回finished

rlock = threading.RLock()

def func(): 
    rlock.acquire()
    for i in range(3): 
        time.sleep(2)
        print(i)
    rlock.release()
    return

def test(): 
    l = []
    for i in range(3): 
        time.sleep(1)
        threading.Thread(target=func).start() 
    print(rlock) # prints <_thread.RLock owner=140092805895936 count=1>
    print(rlock._is_owned()) #prints False 
    if not rlock._is_owned(): 
        return 'finished' #returns 'finished'

test()

更新:具体来说我希望有test()函数在rlock中的所有线程完成之前不会返回。但是我在确定rlock计数器是否增加时遇到了麻烦 - 似乎并不是与之相对应的方法。

1 个答案:

答案 0 :(得分:1)

当使用像_is_owned这样定义不明的内部函数时,最好查看源代码:

def _is_owned(self):
    # Return True if lock is owned by current_thread.
    # This method is called only if __lock doesn't have _is_owned().

主线程不拥有锁,因此函数返回false。

<强>更新

如果您只想等待线程完成,则根本不需要RLock对象。只需使用join()方法:

def func(): 
    for i in range(3): 
        time.sleep(2)
        print(i)
    return

def test(): 
    threads = []
    for i in range(3): 
        time.sleep(1)
        thread = threading.Thread(target=func)
        thread.start()
        threads.append(thread)
    for thread in threads:
        thread.join()
    return 'finished'

test()