为什么我的线程锁不能正常工作?

时间:2020-04-14 19:57:57

标签: python multithreading locking

对于一个作业,我应该创建一个简单的多线程程序,该程序具有三个等待随机时间(介于.1和2秒之间)的线程,然后打印“结束”。我正在尝试使用锁来防止开关使输出混乱,但我的输出似乎仍然是随机的(这意味着锁未按预期工作)。 我的代码是:

import time
from threading import *
import random

lock = Lock()

def one():
    global lock
    time.sleep((random.randint(1,20))/10)
    lock.acquire()
    print("1. end")
    lock.release()

def two():
    global lock
    time.sleep((random.randint(1,20))/10)
    lock.acquire()
    print("2. end")
    lock.release()

def three():
    global lock
    time.sleep((random.randint(1,20))/10)
    lock.acquire()
    print("3. end")
    lock.release()


for i in range(0,100):
    t1 = Thread(target = one)
    t2 = Thread(target = two)
    t3 = Thread(target = three)
    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()

但我的输出是:

 2. end
 3. end
 1. end
 3. end
 2. end
 2. end
 1. end
 3. end
 1. end
 etc...

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您在随机睡眠后获得了锁:

import time
from threading import *
import random

lock = Lock()

def one():
    global lock
    lock.acquire()
    time.sleep((random.randint(1,20))/10)
    print("1. end")
    lock.release()

def two():
    global lock
    lock.acquire()
    time.sleep((random.randint(1,20))/10)
    print("2. end")
    lock.release()

def three():
    global lock
    lock.acquire()
    time.sleep((random.randint(1,20))/10)
    print("3. end")
    lock.release()


for i in range(0,100):
    t1 = Thread(target = one)
    t2 = Thread(target = two)
    t3 = Thread(target = three)
    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()