Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Executing multiple functions simultaneously

I'm trying to run two functions simultaneously in Python. I have tried the below code which uses multiprocessing but when I execute the code, the second function starts only after the first is done.

from multiprocessing import Process
def func1:
     #does something

def func2:
     #does something

if __name__=='__main__':
     p1 = Process(target = func1)
     p1.start()
     p2 = Process(target = func2)
     p2.start()
like image 657
user2739601 Avatar asked Sep 18 '13 05:09

user2739601


People also ask

How do I run two threads simultaneously in Python?

To implement threading in Python, you have to perform three steps: Inherit the class that contains the function you want to run in a separate thread by using the Thread class. Name the function you want to execute in a thread run() . Call the start() function from the object of the class containing the run() method.

How do I run a parallel execution in Python?

Multiprocessing in Python enables the computer to utilize multiple cores of a CPU to run tasks/processes in parallel. Multiprocessing enables the computer to utilize multiple cores of a CPU to run tasks/processes in parallel.


2 Answers

You are doing it correctly. :)

Try running this silly piece of code:

from multiprocessing import Process
import sys

rocket = 0

def func1():
    global rocket
    print 'start func1'
    while rocket < sys.maxint:
        rocket += 1
    print 'end func1'

def func2():
    global rocket
    print 'start func2'
    while rocket < sys.maxint:
        rocket += 1
    print 'end func2'

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

You will see it print 'start func1' and then 'start func2' and then after a (very) long time you will finally see the functions end. But they will indeed execute simultaneously.

Because processes take a while to start up, you may even see 'start func2' before 'start func1'.

like image 117
Shashank Avatar answered Oct 03 '22 07:10

Shashank


This is just what i needed. I know it wasn't asked but i modified shashank's code to suit Python 3 for anyone else looking :)

from multiprocessing import Process
import sys

rocket = 0

def func1():
    global rocket
    print ('start func1')
    while rocket < sys.maxsize:
        rocket += 1
    print ('end func1')

def func2():
    global rocket
    print ('start func2')
    while rocket < sys.maxsize:
        rocket += 1
    print ('end func2')

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

Substitute sys.maxsize for an number then print(rocket)and you can see it count up one at a time. Get to a number and stop

like image 33
Alistair Bendall Avatar answered Oct 03 '22 09:10

Alistair Bendall