I'm new to threading. I wrote this program where I'm trying to execute 2 different functions using threads. I tried to run different functions using the same thread by changing the target and args parameters one after the other :
import threading
import datetime
import Queue
a=Queue.Queue()
b=Queue.Queue()
q=Queue.Queue()
class MyThread(threading.Thread):
def __init__(self,q):
threading.Thread.__init__(self)
self.que=q
t1=threading.Thread(target=self.prints,args=(4,))
t2=threading.Thread(target=self.printy,args=(6,self.que,))
t1.start()
t2.start()
item=self.que.get()
print(item)
print "*"*30
it=item*2
print(it)
t1.join()
def main(self):
t3=threading.Thread(target=self.prints,args=(3,))
t4=threading.Thread(target=self.printy,args=(5,self.que,))
t3.start()
t4.start()
item=self.que.get()
print(item)
print "#"*30
it=item*2
print(it)
t2=threading.Thread(target=self.prints,args=(8,))
t4=threading.Thread(target=self.prints,args=(7,))
t2.start()
t4.start()
t2.join()
t3.join()
t4.join()
def prints(self,i):
while(i>0):
print "i="+str(i)+" "+str(datetime.datetime.now().time())+"\n"
i=i-1
def printy(self,i,b):
r=0
while(i<10):
print "i="+str(i)+" "+str(datetime.datetime.now().time())+"\n"
i=i+1
r=r+i
self.que.put(r)
if __name__=='__main__':
MyThread(a).main()
It executed without throwing any error and also gave me the output I wanted, but I wanted to know if :
- This is the right way to do so? Otherwise, What is the right way to run multiple functions using the same thread as a reusable unit?.
- In a simple program like this, it seems harmless enough but what about more complex programs with many more functions? Any potential problems that could arise?