python线程问题

时间:2013-03-11 13:49:31

标签: python multithreading

我希望将我的线程结果放在列表中。

我有以下示例代码:

def parallelizer_task(processor,input,callback):
    output = processor(input)
    if callback:
        callback(output)
    return output

class ThreadsParallelizer(Parallelizer):

    def parallelize(self,processors,input=None,callback=None):
        threads = []
        for processor in processors:
            t = threading.Thread(target=parallelizer_task,args=(processor,input,callback))
            threads.append(t)
            t.start()
        return threads
parallelizer = ThreadsParallelizer

但我有线程列表的输出为;

* <Thread(Thread-1, started 4418719744)>
* <Thread(Thread-2, started 4425617408)>
* <Thread(Thread-3, started 4429950976)>

有没有办法让线程得到列表?

1 个答案:

答案 0 :(得分:1)

是的,您可以使用例如join。它将强制主线程等待子线程完成工作。然后,您可以将数据存储在threading.Thread个对象中,如下所示:

def parallelizer_task(processor,input,callback):
    output = processor(input)
    if callback:
        callback(output)

    # Attach result to current thread
    thread = threading.currentThread()
    thread.result = output


class ThreadsParallelizer(Parallelizer):

    def parallelize(self,processors,input=None,callback=None):
        threads = []
        for processor in processors:
            t = threading.Thread(...)
            threads.append(t)
            t.start()

        # wait for threads to finish
        for th in threads:
            th.join()

        # do something with results
        results = [th.result for th in threads]
        return results