Trying to learn multi-threading. I downloaded some sample code to play with, and I ended up with this:
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, delay, counter):
super().__init__()
self.threadID = threadID
self.name = name
self.delay = delay
self.counter = counter
threading.Thread.__init__(self)
print(name,"created")
print(self.name,"created")
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.delay, self.counter)
print ("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = myThread(1, "a", 1, 5)
thread2 = myThread(2, "b", 2, 3)
# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exiting Main Thread")
But my output was unexpected, to say the least.
a created
Thread-2 created
b created
Thread-4 created
Starting Thread-2
Starting Thread-4
Thread-2 Mon Jan 14 16:14:29 2013
Thread-2 Mon Jan 14 16:14:30 2013
Thread-4 Mon Jan 14 16:14:30 2013
Thread-2 Mon Jan 14 16:14:31 2013
Thread-2 Mon Jan 14 16:14:32 2013
Thread-4 Mon Jan 14 16:14:32 2013
Thread-2 Mon Jan 14 16:14:33 2013
Exiting Thread-2
Thread-4 Mon Jan 14 16:14:34 2013
Exiting Thread-4
Exiting Main Thread
Why doesn’t self.name evaluate to “a” or “b” after assigning it that way?
namegets reinitialized inthreading.Thread.__init__(self). There is no reason to call parent constructor twice.