尝试运行进程时出现pickle错误

时间:2017-01-10 18:59:33

标签: python pickle

我要做的是一次运行不同进程中的素数分解列表。我有一个正在运行的线程版本,但似乎无法让它与进程一起工作。

import math
from Queue import Queue
import multiprocessing

def primes2(n):
    primfac = []
    num = n
    d = 2
    while d * d <= n:
        while (n % d) == 0:
            primfac.append(d) # supposing you want multiple factors repeated
            n //= d
        d += 1
    if n > 1:
        primfac.append(n)
    myfile = open('processresults.txt', 'a')
    myfile.write(str(num) + ":" + str(primfac) + "\n")
    return primfac

def mp_factorizer(nums, nprocs):
    def worker(nums, out_q):
        """ The worker function, invoked in a process. 'nums' is a
            list of numbers to factor. The results are placed in
            a dictionary that's pushed to a queue.
        """
        outdict = {}
            for n in nums:
            outdict[n] = primes2(n)
        out_q.put(outdict)

    # Each process will get 'chunksize' nums and a queue to put his out
    # dict into
    out_q = Queue()
    chunksize = int(math.ceil(len(nums) / float(nprocs)))
    procs = []

    for i in range(nprocs):
        p = multiprocessing.Process(
                target=worker,
                args=(nums[chunksize * i:chunksize * (i + 1)],
                      out_q))
        procs.append(p)
        p.start()

    # Collect all results into a single result dict. We know how many dicts
    # with results to expect.
    resultdict = {}
    for i in range(nprocs):
        resultdict.update(out_q.get())

    # Wait for all worker processes to finish
    for p in procs:
        p.join()

    print resultdict

if __name__ == '__main__':

    mp_factorizer((400243534500, 100345345000, 600034522000, 9000045346435345000), 4)

我收到了如下所示的泡菜错误:

error image

任何帮助都将非常感谢:)

2 个答案:

答案 0 :(得分:2)

您需要使用multiprocessing.Queue而不是常规Queue+more

这是由于Process没有使用相同的内存空间运行,并且有些对象不能可选择,例如a < em>常规队列(Queue.Queue)。为了解决这个问题,multiprocessing库提供了Queue类,实际上是队列的Proxy

而且,您可以像其他任何方法一样提取def worker(..。这可能是你的主要问题,因为&#34;怎么&#34;一个进程在操作系统级别上分叉。

您还可以使用multiprocessing.Manager +more

答案 1 :(得分:2)

动态创建的函数不能被pickle,因此不能用作the,world,of,flowers,is,a,small,to,be,in 1, 2, 3, 1, 5, 6, 7, 8, 2, 9, 10 的目标,函数Process需要在全局范围内定义,而不是在{{1}的定义中定义}。

相关问题