[英]Python: Multiple threads that can cross-communicate
您可以使用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.