Multiprocessing in Python3

0 min read 115 words
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:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags