Note that there are some explanatory texts on larger screens.

plurals
  1. POmultiple output returned from python multiprocessing function
    primarykey
    data
    text
    <p>I am trying to use multiprocessing to return a list, but instead of waiting until all processes are done, I get several returns from one return statement in mp_factorizer, like this:</p> <pre><code>None None (returns list) </code></pre> <p>in this example I used 2 threads. If I used 5 threads, there would be 5 None returns before the list is being put out. Here is the code: </p> <pre><code>def mp_factorizer(nums, nprocs, objecttouse): if __name__ == '__main__': out_q = multiprocessing.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, objecttouse)) procs.append(p) p.start() # Collect all results into a single result dict. We know how many dicts # with results to expect. resultlist = [] for i in range(nprocs): temp=out_q.get() index =0 for i in temp: resultlist.append(temp[index][0][0:]) index +=1 # Wait for all worker processes to finish for p in procs: p.join() resultlist2 = [x for x in resultlist if x != []] return resultlist2 def worker(nums, out_q, objecttouse): """ 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. """ outlist = [] for n in nums: outputlist=objecttouse.getevents(n) if outputlist: outlist.append(outputlist) out_q.put(outlist) </code></pre> <p>mp_factorizer gets a list of items, # of threads, and an object that the worker should use, it then splits up the list of items so all threads get an equal amount of the list, and starts the workers. The workers then use the object to calculate something from the given list, add the result to the queue. Mp_factorizer is supposed to collect all results from the queue, merge them to one large list and return that list. However - I get multiple returns. </p> <p>What am I doing wrong? Or is this expected behavior due to the strange way windows handles multiprocessing? (Python 2.7.3, Windows7 64bit)</p> <p>EDIT: The problem was the wrong placement of <code>if __name__ == '__main__':</code>. I found out while working on another problem, see <a href="https://stackoverflow.com/questions/14583742/using-multiprocessing-in-a-sub-process">using multiprocessing in a sub process</a> for a complete explanation.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload