An Example of Parallel Processing using Python's "multiprocessing" Module

Comments

5 comments posted
Thank you

Much appreciated. I modified your program to be a little simpler:

#! /usr/bin/env python
import random
import multiprocessing, queue
import time
 
class Worker(multiprocessing.Process):
 
    def __init__(self, work_queue, result_queue):
 
        # base class initialization
        multiprocessing.Process.__init__(self)
 
        # job management stuff
        self.work_queue = work_queue
        self.result_queue = result_queue
        self.kill_received = False
 
    def run(self):
        while not self.kill_received:
 
            # get a task
            #job = self.work_queue.get_nowait()
            try:
                job = self.work_queue.get_nowait()
            except queue.Empty:
                break
 
            # the actual processing
            print("Starting " + str(job) + " ...")
            delay = random.randrange(1,3)
            time.sleep(delay)
 
            # store the result
            self.result_queue.put(delay)
 
if __name__ == "__main__":
 
    num_jobs = 20
    num_processes=8
 
    # run
    # load up work queue
    work_queue = multiprocessing.Queue()
    for job in range(num_jobs):
        work_queue.put(job)
 
    # create a queue to pass to workers to store the results
    result_queue = multiprocessing.Queue()
 
    # spawn workers
    for i in range(num_processes):
        worker = Worker(work_queue, result_queue)
        worker.start()
 
    # collect the results off the queue
    results = []
    for i in range(num_jobs):
        print(result_queue.get())
Posted by Jason (not verified) on Tue, 01/10/2012 - 20:46
Thank You

Very helpful, thanks a lot! Good comments & style :) log_prob-fct is never used? Keep on coding, Enrico

Posted by Enrico (not verified) on Sat, 10/08/2011 - 05:55
Why not keep the worker

Why not keep the worker pointer in a workers list?

Posted by Cees Timmerman (not verified) on Fri, 09/16/2011 - 09:51
This only used 1 CPU on my 12

This only used 1 CPU on my 12 Core Linux machine.
I changed num_jobs = 200000 and num_processes=12

Posted by Anonymous (not verified) on Tue, 02/22/2011 - 13:31
only one core

For some reason your script uses only one core on my machine with WinXP.

Posted by sparrow (not verified) on Thu, 12/23/2010 - 06:19

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a biological visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.