Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start() vs run() for threads in Python?

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()?

like image 271
cjm2671 Avatar asked Apr 22 '14 16:04

cjm2671


People also ask

What is the difference between thread start () and thread run ()?

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.

Why do we call start method in thread instead of run?

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.

What is the relation between thread start and run method?

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.


3 Answers

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.

  • If you want your thread to repeatedly do something, then move the loop into the thread function.
  • If you want multiple threads, then create multiple 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.

like image 124
NPE Avatar answered Oct 16 '22 14:10

NPE


Spawn threads

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.
like image 22
jorgenkg Avatar answered Oct 16 '22 14:10

jorgenkg


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()
like image 40
debug Avatar answered Oct 16 '22 13:10

debug