Reputation: 3501
I have two function, which generate random integer, and sleep for the given interval. However, I would like to sleep those two functions independently, while time.sleep()
pauses the whole Python program.
def fun1():
interval1 = random.randint(2,800)
time.sleep(interval1)
# do other things
def fun2():
interval2 = random.randint(1, 999)
time.sleep(interval2)
# do other things, different than in fun2
How I can sleep a given function, such that when fun1
is paused, fun2
still is doing their thing as long as the time.sleep(interval2)
is not called?
Upvotes: 2
Views: 1561
Reputation: 2936
Simply do like this:
from threading import Thread
thread1 = Thread(target=fun1)
thread2 = Thread(target=fun2)
thread1.start()
thread2.start()
This will start two threads which are independent of the main thread, calling fun1
and fun2
respectively.
Example:
from threading import Thread
import random
import time
starttime = time.time()
def fun1():
interval1 = random.randint(1,5)
time.sleep(interval1)
print "%d sec: Fun1" % (time.time() - starttime)
def fun2():
interval2 = random.randint(1,5)
time.sleep(interval2)
print "%d sec: Fun2" % (time.time() - starttime)
thread1 = Thread(target=fun1)
thread2 = Thread(target=fun2)
thread1.start()
thread2.start()
print "Still doing things!"
Output:
Still doing things!
2 sec: Fun2
4 sec: Fun1
As you can see, the functions are ran but the code still continues executing the print statement after the threads.
Upvotes: 1
Reputation: 24689
Try this:
from multiprocessing import Process
def fun1():
interval1 = random.randint(2,800)
time.sleep(interval1)
# do other things
def fun2():
interval2 = random.randint(1, 999)
time.sleep(interval2)
# do other things
proc1 = Process(target=fun1)
proc2 = Process(target=fun2)
proc1.start()
proc2.start()
proc1.join()
proc2.join()
This will start new Python processes using multiprocessing
to run fun1()
and fun2()
in parallel. The join()
calls will block in the main (parent) process until proc1
and proc2
are complete.
Unfortunately, due to the Global Interpreter Lock, the threading
module doesn't help performance much. But if your functions are mostly just waiting, Thread
s can be appropriate.
Upvotes: 1