簡體   English   中英

Python:可以交叉通信的多個線程

[英]Python: Multiple threads that can cross-communicate

我想運行兩個獨立的函數,這些函數以恆定的時間間隔循環,並同時運行。

Function1需要每60秒循環一次。 然后,我想從Function1觸發Function2的啟動。 然后,Function2每5秒循環一次。 在某個時候,我想停止Function2。

流程圖

最好的解決方案是什么? 謝謝你的幫助。

您可以使用multiprocessing.Process輕松地做到這一點:

from multiprocessing import Process

def function1():
    # ... Initiate loop
    child_process = Process(target=function2)
    child_process.daemon = True # We want function2 to be terminated if function1 exits for some reason
    child_process.start()
    # ... Continue loop execution as normal
    # ... After some time
    child_process.terminate() # This will terminate function2
    # ...
    return

def function2():
    # ... Loop and do stuff
    return

function1()

如果要同步兩個進程,可以使用Lock

from threading import Lock

global_lock = Lock()

def function1():
    child_process = Process(target=function2)
    child_process.daemon = True 
    child_process.start()
    with global_lock:
         # Lock acquired
         print('function1')
    # Lock released
def function2():
    with global_lock:
         # Lock acquired
         print('function2')
    # Lock released

function1()

使用這種方法,您可以保證打印語句永遠不會並行執行,而是順序執行

您可以使用條件變量從一個線程向另一個線程發出信號。

暫無
暫無

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

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