簡體   English   中英

如何使用事件同步兩個持續運行的線程?

[英]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 object 解決此問題,但您可以使用兩個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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM