我在线程 A 中有一个函数,需要等待线程 B 中的函数被调用。
线程 B 中的函数周期性地被调用,所以它只需要等待到下一次被调用。这样我就可以和它同步了。
我将如何做到这一点?
(如果这很琐碎的话,很抱歉。)
这可能是计算机科学的一个原理,没有一个多线程问题是琐碎的。
有各种各样的方法,但其中最简单的一种方法就是使用threading.Event对象。 事件是所谓同步基元中最简单的一种。 更多想法请参见手册中关于线程模块的部分。下面是一个工作示例。
#! python3.8
import threading
import time
t0 = time.time()
def elapsed_time():
return time.time() - t0
class StopMe:
def __init__(self):
self.running = True
def main():
ev1 = threading.Event()
stop = StopMe()
th1 = threading.Thread(target=thread1, args=(ev1, stop))
th1.start()
for _ in range(10):
ev1.wait()
print("The function was just called", elapsed_time())
ev1.clear()
stop.running = False
th1.join()
print("Exit", elapsed_time())
def thread1(event, stop):
def a_function():
event.set()
print("I am the function", elapsed_time())
while stop.running:
time.sleep(1.0)
a_function()
main()
输出。
I am the function 1.0116908550262451
The function was just called 1.0116908550262451
I am the function 2.0219264030456543
The function was just called 2.0219264030456543
I am the function 3.0322916507720947
The function was just called 3.0322916507720947
I am the function 4.033170938491821
The function was just called 4.033170938491821
I am the function 5.043376445770264
The function was just called 5.043376445770264
I am the function 6.043909788131714
The function was just called 6.043909788131714
I am the function 7.054021596908569
The function was just called 7.054021596908569
I am the function 8.06399941444397
The function was just called 8.06399941444397
I am the function 9.064924716949463
The function was just called 9.064924716949463
I am the function 10.066757678985596
The function was just called 10.066757678985596
I am the function 11.076870918273926
Exit 11.076870918273926
这里需要注意一些事情。
一旦你把同步基元放入你的代码中,你需要考虑如何优雅地终止线程,以及如何终止整个应用程序。 在这个例子中,线程通过小 "StopMe "对象,以及通过Event对象进行通信。 请注意,主线程可能需要等待一秒钟,直到辅助线程完成其睡眠功能。 如果线程1在主线程调用join函数之前开始延时,就会发生这种情况。 在我的测试运行中没有发生这种情况,但它可能会发生,这取决于如何给不同线程分配CPU时间片。 如果你不能接受这种情况,你必须写更多的代码来解决这个问题。
还要注意的是,函数调用ev1.wait()会阻塞主线程,直到从二级线程设置事件。 在GUI应用程序中,这不是你想要的。
我用Python3.8运行了这个程序,但是这个程序没有使用任何特定版本的特性,所以它在任何合理的最新版本的Python中都应该是一样的。