Python线程:在线程完成后监视线程并执行其他代码

时间:2015-12-09 02:20:02

标签: python python-multithreading

我有以下代码:

class MyThread(Thread):
    def __init__(self, command, template, env, build_flavor, logger):
        Thread.__init__(self)
        self.command = command
        self.template = template
        self.env = env
        self.build_flavor = build_flavor
        self.logger = logger

    def run(self):
        self.logger.info('Running (%s)...this may take several minutes. Please be patient' % self.build_flavor)
        run_command(self.command, self.template, self.env)
        self.logger.info('Complete (%s)' % self.build_flavor)
        return

然后在另一个类中,当我创建实际线程时:

if self.build_type == 'default':
            threads = []
            for t in self.template:
                modify_template(t)
                build_flavor = self.getmatch(t)
                thread = MyThread(packer, t, self.new_env, build_flavor, self.logger)
                thread.setName(build_flavor)
                thread.start()
                threads.append(thread)
            for thread in threads:
                thread.join()
            vmware_create()
            openstack_create()

不幸的是,在线程是.join()之后,我正在串行调用vmware_create()和openstack_create()。我希望能够在各自的线程完成后执行其中的每一个,这样我就不会在启动其中一个* _create()函数之前等待两个线程完成...然后等待第一个完成在执行第二次

之前

即。现在vmware_create()只有在BOTH线程完成后才会执行,一旦vmware_create()完成,只有openstack_create()才会开始。我希望能够等待相应的线程完成,然后为先前完成的任何线程执行_create()函数,一直等待第二个线程完成,然后一旦完成,立即执行其_create ()函数用于真正的并行化。

我无法弄清楚如何做到这一点并需要帮助。

1 个答案:

答案 0 :(得分:2)

功能是对象。把它们交给线程:

class MyThread(Thread):
    def __init__(self, command, template, env, build_flavor, logger, func=None):
        Thread.__init__(self)
        self.command = command
        self.template = template
        self.env = env
        self.build_flavor = build_flavor
        self.logger = logger
        self.func = func

    def run(self):
        self.logger.info('Running (%s)...this may take several minutes. Please be patient' % self.build_flavor)
        run_command(self.command, self.template, self.env)
        self.logger.info('Complete (%s)' % self.build_flavor)
        # call func if it is there
        if self.func:
            self.func()
        return

现在,我提供了前两个带调用函数的线程:

if self.build_type == 'default':
    threads = []
    funcs = {0: vmware_create, 1: openstack_create}
    for i, t in enumerate(self.template):
        modify_template(t)
        build_flavor = self.getmatch(t)
        func = funcs.get(i, None)
        thread = MyThread(packer, t, self.new_env, build_flavor, 
                          self.logger, func=func)
        thread.setName(build_flavor)
        thread.start()
        threads.append(thread)
    for thread in threads:
        thread.join()

当然,您可以将它们添加到任何其他线程中。