python multiprocessing返回None,不共享计数器

时间:2019-03-29 03:53:38

标签: python multiprocessing

我很难理解如何设置共享计数器,以便获得多处理模块运行的所有进程的合并结果。

我有此代码:

#!/usr/bin/env python2.7

import multiprocessing

def glastvalueFetch(howfarback):
    mylist = []
    justadd = int(1) + int(howfarback)
    return(justadd)

def glvfResults():
    if __name__ == '__main__':
        for howfarback in range(1,8):
            p = multiprocessing.Process(target=glastvalueFetch, args=(howfarback,))
            p.start()
            p.join()

print glvfResults()

现在,当我运行这段代码时,我会回来:

None

有解决此问题的简单方法吗?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

#!/usr/bin/env python2.7

import multiprocessing


def glastvalueFetch(howfarback, results):
    mylist = []
    justadd = int(1) + int(howfarback)
    results.put(justadd)


def glvfResults():
    results = multiprocessing.Queue()
    for howfarback in range(1, 8):
        p = multiprocessing.Process(target=glastvalueFetch, args=(howfarback, results, ))
        p.start()
        p.join()
    while not results.empty():
        print results.get()


if __name__ == '__main__':
    glvfResults()

输出

2
3
4
5
6
7
8