如何使用事件同步两个 contantly 运行 线程?

how to sync two contantly running threads using event?

我正在尝试根据来自线程 2 的事件 运行 线程 1 中的几行。两个线程 运行 不断处于 "while True" 循环中。 问题是我似乎无法 运行 只有在事件发生时才需要的行。

顺便说一句,两个线程都使用共享资源(列表)并且可以使用 Lock 方法进行同步。这对我也不起作用。

frames_list = []
new_frame = Event()
result = 0


def thr1():
    global frames_list
    global frames_list_max_size
    global result
    while True:
        new_frame.set()
        result = result + 1
        new_frame.clear()


def thr2():
    global result
    while True:
        new_frame.wait()
        print(datetime.datetime.now())
        print(result)


threads = []
for func in [thr1, thr2]:
    threads.append(Thread(target=func))
    threads[-1].start()

for thread in threads:
    thread.join()

例如结果:

2019-10-19 22:35:34.150852
1710538
2019-10-19 22:35:34.173803
1722442
2019-10-19 22:35:34.197736
1737844
2019-10-19 22:35:34.214684
1740218
2019-10-19 22:35:34.220664
1749776

我希望: 1. 每次打印之间的时间差为 1 秒。 2. 结果每打印一次加1。

您无法使用一个 Event 对象解决此问题,但您可以使用两个 Event 对象解决此问题:

  1. 通知 result 变量已更改。
  2. 一个通知 result 变量的新值已被消耗。

修改后的代码:

import time

frames_list = []
new_frame = Event()
new_frame_consumed = Event()
result = 0


def thr1():
    global frames_list
    global frames_list_max_size
    global result
    while True:
        result = result + 1
        time.sleep(1)
        new_frame.set()
        new_frame_consumed.wait()
        new_frame_consumed.clear()


def thr2():
    global result
    while True:
        new_frame.wait()
        new_frame.clear()
        print(datetime.datetime.now())
        print(result)
        new_frame_consumed.set()


threads = []
for func in [thr1, thr2]:
    threads.append(Thread(target=func))
    threads[-1].start()

for thread in threads:
    thread.join()