英文:
How to notify when python thread finished
问题
当线程完成时,我想调用回调函数。而且它应该是线程安全的。
我想要一个解决方案,可以在线程完成时调用回调函数,而且它应该是线程安全的。
my_thread = threading.Thread(target=do_work)
my_thread.finished.connect(thread_finished)
my_thread.start()
英文:
I want to call callback function when thread finished. And it should be thread safe
I want solution to call a callback function when thread finished and it should be thread safe.
my_thread = threading.Thread(target=do_work)
my_thread.finished.connect(thread_finished)
my_thread.start()
答案1
得分: 0
你最好的选择是期货。
from concurrent.futures import ThreadPoolExecutor
from time import sleep
def do_work():
sleep(2)
return 10
def im_done(future):
print("未来的结果是", future.result())
with ThreadPoolExecutor() as executor:
future = executor.submit(do_work)
future.add_done_callback(im_done)
英文:
You best bet is futures.
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)
答案2
得分: -1
你可以使用这个对我有用的解决方案。
而且它是线程安全的。
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()
参考此链接 - 通知线程事件
英文:
You can use this solution worked for me.
And it is thread safe.
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()
Refer this - Notify threading events
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论