Skip to content

Instantly share code, notes, and snippets.

@pratik-m
Forked from baojie/hello_multiprocessing.py
Created February 3, 2018 23:38
Show Gist options
  • Save pratik-m/08cb6c18a27f79ffdf138e3dcbaa5561 to your computer and use it in GitHub Desktop.
Save pratik-m/08cb6c18a27f79ffdf138e3dcbaa5561 to your computer and use it in GitHub Desktop.
Python multiprocessing hello world. Split a list and process sublists in different jobs
import multiprocessing
# split a list into evenly sized chunks
def chunks(l, n):
return [l[i:i+n] for i in range(0, len(l), n)]
def do_job(job_id, data_slice):
for item in data_slice:
print "job", job_id, item
def dispatch_jobs(data, job_number):
total = len(data)
chunk_size = total / job_number
slice = chunks(data, chunk_size)
jobs = []
for i, s in enumerate(slice):
j = multiprocessing.Process(target=do_job, args=(i, s))
jobs.append(j)
for j in jobs:
j.start()
if __name__ == "__main__":
data = ['a', 'b', 'c', 'd']
dispatch_jobs(data, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment