3

today i have again a question about multiprocessing... I have a small example code:

import multiprocessing

def function(a):
    v = a**2
    w = a**3
    x = a**4
    y = a**5
    z = a**6


b = [1,2,3,4,5,6,7,8,9,10]

if __name__ == "__main__":
    pool = multiprocessing.Pool(processes=4)
    pool.imap(function, b)

The results should be 5 lists (vlist, wlist, xlist, ylist and zlist). The vlist should have all the v results, the wlist the w results and so on. I want to get all results ordered, so i want to use imap, i hope its the right way. I thought i could use something like append commands but i don't know how...

Thank you for helping, John

theorifice
  • 670
  • 3
  • 9
John28
  • 723
  • 3
  • 8
  • 12
  • Your function doesn't actually do anything since `v, w, x, y, z` don't actually exist. In order to use `imap()`, your function needs to return a value. – theorifice Dec 04 '16 at 02:09

1 Answers1

4

imap() or any mapping function takes one value and 'maps' it to another via the function's return value. In the snippet you posted, function() doesn't return anything.

import multiprocessing

def function(a):
    v = a**2
    w = a**3
    x = a**4
    y = a**5
    z = a**6
    return v, w, x, y, z

b = [1,2,3,4,5,6,7,8,9,10]

pool = multiprocessing.Pool(processes=4)
vals = pool.imap(function, b)

for i in vals:
    print i

Output is:

(1, 1, 1, 1, 1)
(4, 8, 16, 32, 64)
(9, 27, 81, 243, 729)
(16, 64, 256, 1024, 4096)
(25, 125, 625, 3125, 15625)
(36, 216, 1296, 7776, 46656)
(49, 343, 2401, 16807, 117649)
(64, 512, 4096, 32768, 262144)
(81, 729, 6561, 59049, 531441)
(100, 1000, 10000, 100000, 1000000)
theorifice
  • 670
  • 3
  • 9