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()
Code language: Python (python)

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

Import the multiprocessing library

import multiprocessing
Code language: Python (python)

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

def runner(k): print(k)
Code language: Python (python)

Keep track of all the processes

processes = []
Code language: Python (python)

How many processes do you want to run?

for i in range(10):
Code language: Python (python)

Send some arguments to the running function

p = multiprocessing.Process(target=runner, args=(i,))
Code language: Python (python)

Keep track of the processes in a list

processes.append(p)
Code language: Python (python)

Start this process

p.start()
Code language: Python (python)

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

for j in range(len(processes)): processes[j].join()
Code language: Python (python)

Tags:
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
trackback

[…] there are ways to mostly resolve this, such as using the Multiprocessing library, it always seems a bit make-shift to […]