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.pyinMyThread.py, the linegets executed once again (since the module gets loaded), hence a second thread is started.
You could create a guard clause in
main.pyby replacing that line withor better, just pass
var1toMyThreadClassas a parameter to avoid the circular dependency.MyThread.py:
main.py