This simple example ought to get you started, In this case there are two while loops and time.sleep(seconds)
is used to mimic some work
import threading
import time
def func_1():
i = 0
while i<5:
i += 1
time.sleep(1.5) # Do some work for 1.5 seconds
print 'func_1'
def func_2():
i = 0
while i<5:
i += 1
time.sleep(0.5) # Do some work for 0.5 seconds
print 'func_2'
thread1 = threading.Thread(target=func_1)
thread1.start()
thread2 = threading.Thread(target=func_2)
thread2.start()
Produces:
func_2 #0.5 seconds elapsed
func_2 #1.0 seconds elapsed
func_1 #1.5 seconds elapsed finally func_1 :)
func_2 #1.5 threading is not mutithreading! ;)
func_2 #2.0 seconds elapsed
func_2 #2.5 seconds elapsed and since variable i is 5 func_2 is no more :(
func_1 #3.0 seconds elapsed
func_1 #4.5 seconds elapsed
func_1 #6.0 seconds elapsed
func_1 #7.5 seconds elapsed
Edit:
What I meant by saying threading is not mutithreading! ;)
is that if by any chance you think that both func_1
and func_2
are executed concurrently at 1.5 seconds
it is not True as threads run in the same memory space but if you use multiprocessing
they have separate memory spaces and would run concurrently
Finally, For your case you should use threading
as its more suitable for these type of tasks