当不再满足其条件时调用带有lock.aquire()的函数

时间:2018-08-02 15:41:00

标签: python python-3.x python-multithreading

我找到了这个小问题的 a 解决方案,但是我仍然想知道为什么它首先出现。

在我的代码中,我(认为我)有一个主线程以及另一个线程。

从处理主线程的函数中,如果接收到的输入为“”,则调用获取a /锁的函数(function_a)。

这是我的代码:

import time
import threading

class Some_Class:
    def __init__(self):
        self.lock = threading.Lock()

    def function_a(self):
        self.lock.acquire()
        print("function_A called")
        self.lock.release()

    def function_b(self):
        self.lock.acquire()
        print("function_B called")
        self.lock.release()

some_class = Some_Class()

def main_thread():
    while True:
        if input() == "":
            some_class.function_a()
        time.sleep(0.5) # <-----

def thread():
    while True:
        some_class.function_b()
        time.sleep(0.5)

def main():
    threading.Thread(target=thread).start()
    main_thread()

if __name__ == "__main__":
    main()

因此,当我在main_thread()函数中删除time.sleep(0.5)时,问题就消失了。但是,我仍然不明白为什么在main_thread()函数中有time.sleep(0.5)时,在用户按住Enter键几秒钟后会调用function_a一段时间。

有人可以解释这种现象的原因吗?

谢谢。

编辑:如果我不清楚我的问题:

  • 当main_function()中没有time.sleep()时,一旦不再按下enter键,function_a就会停止打印。但是当time.sleep()存在时,function_a继续打印一段时间。 我想知道为什么会这么做...

0 个答案:

没有答案