Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python锁Vs RLock_Python_Multithreading_Locking - Fatal编程技术网

Python锁Vs RLock

Python锁Vs RLock,python,multithreading,locking,Python,Multithreading,Locking,我知道RLock在发布之前可以被多次获取。我的问题是在下面的例子中,我可以使用多个锁而不是使用RLock吗。我运行了它,它运行得很好 import threading ##declare two locks, is that good way to do like this or using RLock outer_lock = threading.Lock() lock = threading.Lock() t = [] def get_first_part(): lock.acq

我知道RLock在发布之前可以被多次获取。我的问题是在下面的例子中,我可以使用多个锁而不是使用RLock吗。我运行了它,它运行得很好

import threading

##declare two locks, is that good way to do like this or using RLock
outer_lock = threading.Lock()
lock = threading.Lock()
t = []

def get_first_part():
    lock.acquire()
    global t
    try:
        t.append('first')
    finally:
        lock.release()
    return t

def get_second_part():
    lock.acquire()
    global t
    try:
        t.append('second')
    finally:
        lock.release()
    return t


def get_both_part():
    outer_lock.acquire()
    try:
        first = get_first_part()
        second = get_second_part()
    finally:
        outer_lock.release()
    return first, second

t1 = threading.Thread(target=get_both_part)
t2 = threading.Thread(target=get_both_part)

t1.start()
t2.start()
t1.join()
t2.join()

问题是,为什么要使用多个锁而不是一个锁?它使程序更容易出错和死锁,使代码更复杂,不能很好地扩展到动态深度递归锁定,我不希望它减少争用或更快地工作(尽管我不会在没有测试的情况下排除这种可能性)。在这种情况下,我认为它是等效的。当您还使用“三”时,它不需要产生等效的预期行为。我建议使用上下文管理器“with”-而不是try:finally: