如何在Python线程完成时通知

问题描述 投票:0回答:1

我想在线程完成时调用回调函数。而且它应该是线程安全的

我希望解决方案在线程完成时调用回调函数,并且它应该是线程安全的。

    my_thread = threading.Thread(target=do_work)
my_thread.finished.connect(thread_finished()
my_thread.start()

python multithreading callback
1个回答
0
投票

你最好的选择是期货。

from concurrent.futures import ThreadPoolExecutor
from time import sleep

def do_work():
    sleep(2)
    return 10

def im_done(future):
    print("Result of future is", future.result())

with ThreadPoolExecutor() as executor:
    future = executor.submit(do_work)
    future.add_done_callback(im_done)
© www.soinside.com 2019 - 2024. All rights reserved.