In Python threading, how I can I track a thread's completion?

前端 未结 7 1887
暖寄归人
暖寄归人 2020-12-19 04:52

I\'ve a python program that spawns a number of threads. These threads last anywhere between 2 seconds to 30 seconds. In the main thread I want to track whenever each thread

7条回答
  •  梦毁少年i
    2020-12-19 05:42

    Here's a variation on @detly's answer that lets you specify the messages from your main thread, instead of printing them from your target functions. This creates a wrapper function which calls your target and then prints a message before terminating. You could modify this to perform any kind of standard cleanup after each thread completes.

    #!/usr/bin/python
    
    import threading
    import time
    
    def target1():
        time.sleep(0.1)
        print "target1 running"
        time.sleep(4)
    
    def target2():
        time.sleep(0.1)
        print "target2 running"
        time.sleep(2)
    
    def launch_thread_with_message(target, message, args=[], kwargs={}):
        def target_with_msg(*args, **kwargs):
            target(*args, **kwargs)
            print message
        thread = threading.Thread(target=target_with_msg, args=args, kwargs=kwargs)
        thread.start()
        return thread
    
    if __name__ == '__main__':
        thread1 = launch_thread_with_message(target1, "finished target1")
        thread2 = launch_thread_with_message(target2, "finished target2")
    
        print "main: launched all threads"
    
        thread1.join()
        thread2.join()
    
        print "main: finished all threads"
    

提交回复
热议问题