多线程如何知道所有任务何时完成(Python)

时间:2013-01-13 17:58:45

标签: python multithreading

这是我的问题:什么是最好和更聪明的方式来了解“当一组特定任务完成后,能够根据刚完成的组启动其他任务”

例如我有这棵树,所以当A完成时,我可以启动H和B等... 但是在我的小树下,你还需要知道每个被认为完成的字母必须完成某些任务(也是并行)

           A
         /   \
       H       B
     /        /  \
   C         F     D 

所以一个完整的例子是:

- Starting A
     - Starting instance 1 of A
     - Starting instance 2 of A
     - Starting instance 3 of A
     - Instance 1 of A Finished
     - Instance 2 of A Finished
     - Instance 3 of A Finished

- Starting H
- Starting B
     - Starting instance 1 of H
     - Starting instance 2 of H
     - Starting instance 1 of B
     - Starting instance 3 of H
     - B has completed all its tasks
- Starting F
     - Starting instance 4 of H
     - H has completed all its tasks
- Starting C
etc...

所以要恢复我的问题:哪个是最好的结构,等待A的所有任务完成才能启动B和H?

目前这就是我正在基于特定基督徒的lib线程池使用回调进行的操作 http://www.chrisarndt.de/projects/threadpool/

对于每个字母,我都有要完成的任务数量,所以我创建了一个像这样的字典

instances_count = {"A":[0,5],"B":[0,2],"H":[0,3],"C":[0,0],"D":[0,1]}

这是我的第一个请求

requests = threadpool.makeRequests(do_something, ["A"],print_result)
do_something结束时将调用

print_result

def do_something(data):

    Here I just retrieve what the Tasks of A and make an other request to parallelize them

   command_requests = threadpool.makeRequests(execute_command, argument_list,instance_finished)


def execute_command(data):
   Here I Do what the task has to do and when it is done i return the datas
   return data

def instance_finished():
    And here what I do is that I will use that instance_count to add +1 when A task reletated to a Letter finishes...

   Global.Lock()
   instances_count[Letter][0] = instances_count[Letter][0] + 1
   Global.unLock()

我检查instances_count [Letter] [0] == instances_count [Letter] [1]是否意味着A的所有任务都已完成,我可以“开始”字母B和H

那么有人可以告诉我这是否是一个好的解决方案?如果否我怎样才能改善这一点?

谢谢!

1 个答案:

答案 0 :(得分:0)

我建议您使用Mutltiprocessing Module

设置工作池并使用apply_async或类似的映射函数添加任务。

apply_async会返回AsyncResult个对象。 AsyncResult对象具有以下方法。

  

等待([超时])

     
    

等到结果可用或直到超时     秒过了。

  
     

ready()

     
    

返回通话是否已完成。

  

上面的链接都是。祝你好运。