Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中有序并行运行_Python_Multithreading - Fatal编程技术网

在Python中有序并行运行

在Python中有序并行运行,python,multithreading,Python,Multithreading,如何使Python中的程序运行如下: 主要内容: 任务1->任务2->任务3,任务4->任务5 说明:我先运行任务1,然后运行任务2。完成任务2后,任务3和任务4并行运行。 完成任务3后,任务4立即完成。然后运行任务5 我试过了 try: thread.start_new_thread.task3 thread.start_new_thread.task4 except: print " Unable to run " 但它是这样运作的: 任务1->任务2->任务5任务3和

如何使Python中的程序运行如下:

主要内容: 任务1->任务2->任务3,任务4->任务5

说明:我先运行任务1,然后运行任务2。完成任务2后,任务3和任务4并行运行。 完成任务3后,任务4立即完成。然后运行任务5

我试过了

try:
   thread.start_new_thread.task3
   thread.start_new_thread.task4
except:
    print " Unable to run "
但它是这样运作的:


任务1->任务2->任务5任务3和任务4从程序开始和结束时工作^ ^

使用此代码,您可以通过调用join来创建具有先例的线程。线程将被锁定,直到前一个线程完成。请记住,不能对尚未启动的线程调用join。task1到task5是调用您必须定义的正常过程的实际过程

要在task3完成时使task4完成,请创建一个全局变量并使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 "

将try放在任务2之后和任务5之前。在任务5之前,记得加入他们。非常感谢,我会尝试。这是一个有趣的设置!您启动线程的顺序是显而易见的,合乎逻辑的,但是假设您在1之前启动了线程2-为什么这不起作用?线程2似乎会阻止等待线程1完成,不是吗?因为如果这样做,就会出现运行时错误;无法加入尚未启动的线程。这样做会引发运行时错误。这就是为什么orderOK;这是因为您只能连接已启动的线程,而不能连接已创建但尚未启动的线程吗?--我知道答案是肯定的+1,顺便说一句。我建议在答案中添加此信息作为额外信息。然后我们可以把评论清理干净。没错。连接一个尚未创建的线程是一个内在的无意义xD,在最好的情况下,变量会出现一个NameError,但是连接一个尚未启动的已创建线程会产生一个RuntimeError,并且只有这个意思,所以如果你陷入其中,你就会知道这是因为连接。