如何在Python中锁定部分方法

时间:2017-03-24 16:23:03

标签: python multithreading python-2.7 python-multithreading

我想锁定方法的一部分(&#34之后的部分;等待获取锁定"应该只在第一个线程释放锁之后运行)。无论lock.acquire()如何,两个线程都会独立运行。

我无法弄清楚为什么这不起作用。 stackoverflow中的示例类似但不完全类似于此。我只是瞥见为什么需要这个:我没有明确的共享资源,我只是想阻止2个python线程运行相同的代码,因为在我正在研究的系统中,它们可能是潜在的使系统处于不稳定状态。

import threading, time

def test(name):
    lock = threading.Lock()

    print(name + " - Starting thread")
    print(name + " - Waiting to acquire lock")
    lock.acquire(True)
    try:
        print(name + " - Lock acquired!")
        for i in range(10):

            print(name + " - " + str(i))
            print("")
            time.sleep(1)
    finally:
        lock.release()
        print(name + " - Lock released")

def main():

    t1 = threading.Thread(target=test, args=["#1_Thread"])
    t2 = threading.Thread(target=test, args=["#2_Thread"])

    t1.start()
    time.sleep(3)
    t2.start()

main()

2 个答案:

答案 0 :(得分:4)

您的线程每个都创建并锁定自己的独立锁:

let

这不会提供相互排斥。两个线程可以同时锁定不同的锁而不会发生冲突;当两个线程试图锁定相同的锁时,锁只会执行任何操作。

创建一个锁并将其提供给两个线程。在您使用它时,def test(name): lock = threading.Lock() ... 语句通常比with块更清晰地确保清理。 That'll lock the lock when execution enters the with and unlock it when execution leaves

finally

答案 1 :(得分:-2)

您创建的锁定对象是您的函数的本地对象,因此不会共享:

lock = threading.Lock()

将您的锁定义为全局,并将共享

import threading, time
lock = threading.Lock()

def test(name):
    global lock

    print(name + " - Starting thread")
    print(name + " - Waiting to acquire lock")
    lock.acquire(True)
    try:
        print(name + " - Lock acquired!")
        for i in range(10):

            print(name + " - " + str(i))
            print("")
            time.sleep(1)
    finally:
        lock.release()
        print(name + " - Lock released")

def main():

    t1 = threading.Thread(target=test, args=["#1_Thread"])
    t2 = threading.Thread(target=test, args=["#2_Thread"])

    t1.start()
    time.sleep(3)
    t2.start()

main()