I'm new to Python so my apologies if this is something obvious.
I'm trying to build multi threaded application, however when I want to create a thread I get two instead of one.
MyThread.py
from threading import Thread
import time
class MyThreadClass(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
print "starting " + self.getName() + "\n"
from main import var1
while True:
print self.getName() + " is running\n"
print "value: " + var1 + "\n"
time.sleep(1)
main.py
from MyThread import MyThreadClass
var1 = "Test"
MyThreadClass().start()
The output I get
Thread-1 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
.....
Why is it happening? I noticed that if I replace MyThreadClass().start() with MyThreadClass().run() I get 2 threads but only one of them keeps running
Thread-1 is running
Thread-2 is running
Thread-2 is running
Thread-2 is running
Thread-2 is running
.....
Any idea what's wrong with the code?
When you import main.py in MyThread.py, the line
MyThreadClass().start()
gets executed once again (since the module gets loaded), hence a second thread is started.
You could create a guard clause in main.py by replacing that line with
if __name__ == "__main__":
MyThreadClass().run()
or better, just pass var1 to MyThreadClass as a parameter to avoid the circular dependency.
MyThread.py:
from threading import Thread
import time
class MyThreadClass(Thread):
def __init__(self, var1):
Thread.__init__(self)
self.var1 = var1
def run(self):
print "starting " + self.getName() + "\n"
while True:
print self.getName() + " is running\n"
print "value: " + self.var1 + "\n"
time.sleep(1)
main.py
from MyThread import MyThreadClass
if __name__ == "__main__":
MyThreadClass("Test").run()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With