提问人:Manoj gowda 提问时间:8/10/2023 最后编辑:Manoj gowda 更新时间:8/20/2023 访问量:67
python线程完成时如何通知
How to notify when python thread finished
问:
我想在线程完成后调用回调函数。它应该是线程安全的
我希望解决方案在线程完成时调用回调函数,并且它应该是线程安全的。
my_thread = threading.Thread(target=do_work)
my_thread.finished.connect(thread_finished)
my_thread.start()
答:
0赞
Frank Yellin
8/10/2023
#1
你最好的选择是期货。
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)
评论
0赞
Manoj gowda
8/20/2023
我想在pyqt中使用。在回调函数中,如果我调用 qt widget,它会抛出错误。而且它不是线程安全的。谢谢你的回答
-1赞
Mahalakshmi D
8/12/2023
#2
您可以使用这个对我有用的解决方案。 而且它是线程安全的。
import time
from threading import Thread
from pyrvsignal import Signal
class MyThread(Thread):
started = Signal()
finished = Signal()
def __init__(self, target, args):
self.target = target
self.args = args
Thread.__init__(self)
def run(self) -> None:
self.started.emit()
self.target(*self.args)
self.finished.emit()
def do_my_work(details):
print(f"Doing work: {details}")
time.sleep(10)
def started_work():
print("Started work")
def finished_work():
print("Work finished")
thread = MyThread(target=do_my_work, args=("testing",))
thread.started.connect(started_work)
thread.finished.connect(finished_work)
thread.start()
参考此内容 - 通知线程事件
评论