The best solution for your problem is to use Pool . Using Queue and having a separate “load queue” function is probably too large.
Here's a slightly rebuilt version of your program, this time with just 2 processes coralled in Pool . I believe this is the easiest way, with minimal changes to the source code:
import multiprocessing import time data = ( ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'], ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7'] ) def mp_worker((inputs, the_time)): print " Processs %s\tWaiting %s seconds" % (inputs, the_time) time.sleep(int(the_time)) print " Process %s\tDONE" % inputs def mp_handler(): p = multiprocessing.Pool(2) p.map(mp_worker, data) if __name__ == '__main__': mp_handler()
Note that the mp_worker() function now takes a single argument (a tuple of the two previous arguments), because the map() function blocks your input in the sublists, each sublist is set as one argument to your working function.
Output:
Processs a Waiting 2 seconds Processs b Waiting 4 seconds Process a DONE Processs c Waiting 6 seconds Process b DONE Processs d Waiting 8 seconds Process c DONE Processs e Waiting 1 seconds Process e DONE Processs f Waiting 3 seconds Process d DONE Processs g Waiting 5 seconds Process f DONE Processs h Waiting 7 seconds Process g DONE Process h DONE
Edit as per @Thales comment below:
If you want to "block the restriction for each pool" so that your processes run in tandem pairs, ala:
Waiting B Waiting | Done, D done | Waiting, Waiting D | C done, D done | ...
then change the function of the handler to start pools (from 2 processes) for each data pair:
def mp_handler(): subdata = zip(data[0::2], data[1::2]) for task1, task2 in subdata: p = multiprocessing.Pool(2) p.map(mp_worker, (task1, task2))
Now your output:
Processs a Waiting 2 seconds Processs b Waiting 4 seconds Process a DONE Process b DONE Processs c Waiting 6 seconds Processs d Waiting 8 seconds Process c DONE Process d DONE Processs e Waiting 1 seconds Processs f Waiting 3 seconds Process e DONE Process f DONE Processs g Waiting 5 seconds Processs h Waiting 7 seconds Process g DONE Process h DONE