Categories
Python Answers

How to run functions in parallel with Python?

Spread the love

Sometimes, we want to run functions in parallel with Python.

In this article, we’ll look at how to run functions in parallel with Python.

How to run functions in parallel with Python?

To run functions in parallel with Python, we can use the multiprocessing module.

For instance, we write:

from multiprocessing import Process


def func1():
    print('func1: starting')
    for i in range(10000000):
        pass
    print('func1: finishing')


def func2():
    print('func2: starting')
    for i in range(10000000):
        pass
    print('func2: finishing')


if __name__ == '__main__':
    p1 = Process(target=func1)
    p1.start()
    p2 = Process(target=func2)
    p2.start()
    p1.join()
    p2.join()

We have func1 and func2 functions that we want to run.

Then we use the Process class to create the processes from the functions.

Then we call start to start the processes.

And we call join to join each process.

Therefore, we see:

func1: starting
func2: starting
func1: finishing
func2: finishing

printed.

Conclusion

To run functions in parallel with Python, we can use the multiprocessing module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *