Reputation: 445
I have the following program that I wrote to implement thread as a class.
import threading
import datetime
import time
class MyThread(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
self.i=i
def prints(self):
while(self.i>0):
print "i="+str(self.i)+" "+str(datetime.datetime.now().time())+"\n"
self.i=self.i-1
time.sleep(1)
return
t1=MyThread(3)
t2=MyThread(5)
time.sleep(1)
t1.start()
t2.start()
#t1.join()
#t2.join()
Even though it executes without throwing any errors, I don't see the output I'm expecting i.e, prints of i=3 to 1 in one thread and prints of i=5 to 1 in another thread. In fact, there is no output at all. And the code looks fine to me. I even tried adding sleep statements, no avail. What could possibly have gone wrong?
Upvotes: 0
Views: 63
Reputation: 4528
You never call prints
function , you should call prints
in run
function that overrides from Thread
class:
class MyThread(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
self.i=i
def run(self):
self.prints()
and also you should import datetime
and this is output:
i=3 16:55:36.903809
i=5 16:55:36.904809
i=2 16:55:37.966870
i=4 16:55:37.967870
i=1 16:55:38.972927
i=3 16:55:38.973927
i=2 16:55:39.979985
i=1 16:55:40.984042
Upvotes: 3
Reputation: 20336
Nowhere do you call prints()
; you merely define it. If you call it run
instead, the threading class will call it. You could also keep the name but define a separate run
method that calls it.
Upvotes: 2