-2

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()

2 Answers2

0

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)
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • I want to use in pyqt. In callback function if I call qt widget it throws error. And it is not thread safe. Thanks for your answer – Manoj gowda Aug 20 '23 at 14:55
-1

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