这是@detly答案的一种变体,它使您可以从主线程中指定消息,而不是从目标函数中打印消息。这将创建一个包装函数,该函数调用您的目标,然后在终止之前打印一条消息。您可以将其修改为在每个线程完成之后执行任何类型的标准清除。
#!/usr/bin/pythonimport threadingimport timedef 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 threadif __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"
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)