Multiprocessing in Python3

import multiprocessing

def runner(k):
  print(k)

processes = []
for i in range(10):
  p = multiprocessing.Process(target=runner, args=(i,))
  processes.append(p)
  p.start()

for j in range(len(processes)):
  processes[j].join()

Now that you have the code; let’s explain:

Import the multiprocessing library

import multiprocessing

Define the function that will run each time a process is executed

def runner(k):
  print(k)

Keep track of all the processes

processes = []

How many processes do you want to run?

for i in range(10):

Send some arguments to the running function

  p = multiprocessing.Process(target=runner, args=(i,))

Keep track of the processes in a list

  processes.append(p)

Start this process

  p.start()

Loop through all processes running and wait for them to end before quitting

for j in range(len(processes)):
  processes[j].join()

Tags:

Leave a Reply

Your email address will not be published.