【问题标题】:Why aren't my thread locks working properly?为什么我的线程锁不能正常工作?
【发布时间】:2020-04-14 19:57:57
【问题描述】:

对于一个分配,我应该创建一个简单的多线程程序,它有三个线程等待随机时间(0.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、2、3 的任意组合获得 3 个一组的打印件。我假设您显示的输出只是在屏幕上滚动的中间的某个地方。如果您想避免像“1. 2. eendnd”这样多个线程同时调用打印的乱码输出,这是锁定的正确方法。
  • 顺便说一句,import * 通常是不好的做法。

标签: python multithreading locking


【解决方案1】:

你在随机睡眠后获得锁:

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()

【讨论】:

  • 这将随机阻塞所有线程,基于哪个线程最先获得锁。我看不出这是如何解决任何问题的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多