I'm a little bit confused.
I'm trying to start a thread in a loop, i.e.:
while True:
my_thread.start()
I'm a little confused because I've had it working with my_thread.run()
, but when I swapped it to start() it fails to start more than one thread. Is my .run() not actually a separate thread, and if not what should I be doing? Lastly, can I pass variables into start()?
start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place.
Calling start () will start a new Thread and calling run() method does not start a new Thread. If you call start() method on Thread, Java Virtual Machine will call run() method and two threads will run concurrently now - Current Thread and Other Thread or Runnable implementation.
Java Thread start() method The start() method internally calls the run() method of Runnable interface to execute the code specified in the run() method in a separate thread. The thread moves from New State to Runnable state.
You are correct in that run()
does not spawn a separate thread. It runs the thread function in the context of the current thread.
It is not clear to me what you are trying to achieve by calling start()
in a loop.
Thread
objects (and call start()
once on each of them).Finally, to pass arguments to a thread, pass args
and kwargs
to the Thread
constructor.
You can not spawn multiple threads like this:
while True:
my_thread.start() # will start one thread, no matter how many times you call it
Use instead:
while True:
ThreadClass( threading.Thread ).start() # will create a new thread each iteration
threading.Thread( target=function, args=( "parameter1", "parameter2" ))
def function( string1, string2 ):
pass # Just to illustrate the threading factory. You may pass variables here.
Please read threading code and docs. start() must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control. run() will be called by start() in the context as follow:
def start(self):
....
_start_new_thread(self._bootstrap, ())
....
def _bootstrap(self):
....
self._bootstrap_inner()
....
def _bootstrap_inner(self):
...
self.run()
...
Let's a demo for start() and run().
class MyThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(MyThread, self).__init__(*args, **kwargs)
def run(self):
print("called by threading.Thread.start()")
if __name__ == '__main__':
mythread = MyThread()
mythread.start()
mythread.join()
$ python3 threading.Thread.py
called by threading.Thread.start()
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