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 Process class.

For instance, we write

from multiprocessing import Process


def func1():
    print("func1: starting")
    for i in xrange(10000000):
        pass
    print("func1: finishing")


def func2():
    print("func2: starting")
    for i in xrange(10000000):
        pass
    print("func2: finishing")


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

to create 2 functions func1 and func2.

Then we create Process objects that runs these functions when we start them.

Next, we call start on each Process object to start the processes.

Then we use the join method to block the execution of the main process until the process whose join is called terminates.

Conclusion

To run functions in parallel with Python, we can use the Process class.

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 *