代码之家  ›  专栏  ›  技术社区  ›  Manoj gowda

如何在python线程完成时通知

  •  -1
  • Manoj gowda  · 技术社区  · 2 年前

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

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

    my_thread = threading.Thread(target=do_work)
    my_thread.finished.connect(thread_finished)
    my_thread.start()
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Frank Yellin    2 年前

    你最好的选择是期货。

    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
  •   Mahalakshmi D    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()
    
    

    请参阅- Notify threading events