How to pass and run a callback method in Python

前端 未结 3 1094
孤街浪徒
孤街浪徒 2020-12-28 14:34

I have a Manager (main thread), that creates other Threads to handle various operations. I would like my Manager to be notified when a Thread it created ends (when run() met

3条回答
  •  忘掉有多难
    2020-12-28 14:57

    If you want the main thread to wait for children threads to finish execution, you are probably better off using some kind of synchronization mechanism. If simply being notified when one or more threads has finished executing, a Condition is enough:

    import threading
    
    class MyThread(threading.Thread):
        def __init__(self, condition):
            threading.Thread.__init__(self)
            self.condition = condition
    
        def run(self):
            print "%s done" % threading.current_thread()
            with self.condition:
                self.condition.notify()
    
    
    condition = threading.Condition()
    condition.acquire()
    
    thread = MyThread(condition)
    thread.start()
    
    condition.wait()
    

    However, using a Queue is probably better, as it makes handling multiple worker threads a bit easier.

提交回复
热议问题