有了这个代码,您可以创建具有优先权的线程通过调用join
。线程将被锁定,直到前面的线程完成。请记住,您无法在尚未开始的线程上调用连接。 task1
到task5
是要调用的实际过程(您必须定义的常规过程)。
要使task4在task3完成时完成,请创建一个全局变量并使task4监视该变量。 task3必须设置task4必须等待的值。这取决于你如何做到这一点,但没有内置的机制。如果你不想要全局变量,那么使用许多着名的Python机制来避免这种情况(例如,每个可调用对象可能是一个实例的绑定方法)。
class CustomThread(threading.Thread):
def __init__(group=None, target=None, name=None, prev=(), args=(), kwargs={}):
super(CustomThread, self).__init__(group, target, name, args, kwargs)
self.prev_threads = prev
def run():
for prev in self.prev_threads:
prev.join()
super(CustomThread, self).run()
try:
thread1 = CustomThread(target=task1)
thread2 = CustomThread(prev=[thread1], target=task2)
thread3 = CustomThread(prev=[thread2], target=task3)
thread4 = CustomThread(prev=[thread2], target=task4)
thread5 = CustomThread(prev=[thread3,thread4], target=task5)
#start the threads in this order or you'll get a RuntimeError
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread5.start()
except:
print " unable to run "
在任务2之后和任务5之前放置尝试。在任务5之前,请记住加入它们。 – HuStmpHrrr 2014-10-29 14:46:13
非常感谢,我会尽力的。 – PhuongHoang 2014-10-29 16:27:56