2017-01-10 2 views
1

제가하려고하는 일은 다른 프로세스에서 한 번에 소수 분해 목록을 실행하는 것입니다. 스레드 버전이 작동하지만 프로세스와 함께 작동하지 않을 수 있습니다.프로세스를 실행하려고 할 때 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

는 대신 일반 Queuemultiprocessing.Queue를 사용해야합니다. +more

이 프로세스는 동일한 메모리 공간를 사용하여 실행되지 않습니다 때문입니다 및 pickable 수없는 일부 개체는 A 일반 큐 (Queue.Queue)처럼 존재한다. 이를 극복하기 위해 multiprocessing 라이브러리는 Queue 클래스를 제공하며 실제로는 Proxy입니다.

또한 다른 방법으로 def worker(..을 추출 할 수 있습니다. 이것은 프로세스가 OS 레벨에서 "어떻게"포크를하기 때문에 주요 문제 일 수 있습니다.

multiprocessing.Manager+more을 사용할 수도 있습니다.

+0

Queue()가 multiprocessing.queue()로 변경되었습니다. 이제 AttributeError가 나타납니다. 'module'객체에 'queue'오류가 없습니다. –

+0

설명서 및 답변을주의 깊게 확인하고, 'multiprocessing.queue'를 대문자, 그것은'멀티 프로세싱 .Queue' –

+0

고마워요! 당신의 솔루션과 Tadhg에 의해 아래에 게시 된 솔루션의 조합이 그것을 고쳤습니다. 고마워요. :) –

2

동적으로 생성 된 함수는 절편 될 수 없으므로 의 대상으로 사용할 수 없으며 worker 함수는 mp_factorizer 정의 대신 전역 범위에 정의해야합니다.

+0

라파엘과 결합하여 고맙습니다! –

관련 문제