51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

当Python线程完成时如何通知

英文:

How to notify when python thread finished

问题 {#heading}

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

我想要一个解决方案,可以在线程完成时调用回调函数,而且它应该是线程安全的。

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 {#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 {#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


赞(1)
未经允许不得转载:工具盒子 » 当Python线程完成时如何通知