多线程。 MyLock.acquire(),应该放置哪个锁?

时间:2017-04-18 11:52:25

标签: python multithreading

问候..

在以下代码中,在尝试之前或之后应该获取 lock ?哪个有效?代码工作正常,但是,我想确保我的代码完全锁定线程。

def DoThis(name, repeat):
    global x, MyLock
    MyLock.acquire()
    try:
        print ("Thread ",name, "Has Acquired the LOCK")
        while repeat > 0:
            x = x * 2
            print (" X = ", x)
            repeat -= 1
    except:
        raise #raise exception
    finally:
        MyLock.release()
        print("Thread ", name, "Has Released the LOCK")

def DoAfter(name, repeat):
    global x, MyLock
    MyLock.acquire()
    try:
        print ("Thread ",name, "Has Acquired the LOCK")
        while repeat > 0:
            x = x + 1
            print (" X = ", x)
            repeat -= 1
    except:
        raise #raise exception
    finally:
        MyLock.release()
        print("Thread ", name, "Has Released the LOCK")

def main():
    print("Hello World")
    global x, MyLock
    x = 2
    MyLock = threading.Lock()
    # My_Thread = threading.Thread(target = MyFunc)
    # We can modify the previous line by adding a thread name
    My_Thread_1 = threading.Thread(target = DoThis, args = ('My Thread 1',20))
    My_Thread_1.start()
    My_Thread_2 = threading.Thread(target = DoAfter, args = ('My Thread 2', 20))
    My_Thread_2.start()
    print ("Final X = ", x )

1 个答案:

答案 0 :(得分:0)

我希望你知道locks的目的。在您的情况下,如果您想处理锁定例外,例如could not obtain lock,那么您可以在try块中使用lock并且可以处理它。

我建议这样做,因为在db transactions这样的重要工作中,最好在try块中使用锁,因为您可以通过还原db事务来处理锁异常。所以最好在try块中处理锁。