Basics of multithreading

suggest change

Using the threading module, a new thread of execution may be started by creating a new threading.Thread and assigning it a function to execute:

The target parameter references the function (or callable object) to be run. The thread will not begin execution until start is called on the Thread object.

Starting a Thread

my_thread.start() # prints 'Hello threading!'

Now that my_thread has run and terminated, calling start again will produce a RuntimeError. If you’d like to run your thread as a daemon, passing the daemon=True kwarg, or setting my_thread.daemon to True before calling start(), causes your Thread to run silently in the background as a daemon.

Joining a Thread

In cases where you split up one big job into several small ones and want to run them concurrently, but need to wait for all of them to finish before continuing, Thread.join() is the method you’re looking for.

For example, let’s say you want to download several pages of a website and compile them into a single page. You’d do this:

A closer look at how join() works can be found here.

Create a Custom Thread Class

Using the threading.Thread class, we can define a custom thread class. We must override the run method in the subclass.

from threading import Thread
import time

class Sleepy(Thread):

    def run(self):
        time.sleep(5)
        print("Hello from Thread")

if __name__ == "__main__":
    t = Sleepy()
    t.start()      # start() calls the subclass run method.
    # print 'The main program continues to run in foreground.'
    t.join()
    print("The main program continues to run in the foreground.")

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents