我找到了这个小问题的 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一段时间。
有人可以解释这种现象的原因吗?
谢谢。
编辑:如果我不清楚我的问题: