Threading and threads

In Python you can create threads using the thread module in Python 2.x or _thread module in Python 3.  We will use the threading module to interact with it.

A thread is an operating system process with different features than a normal process:

  • threads exist as a subset of a process
  • threads share memory and resources
  • processes have a different address space (in memory)

When would you use threading? Usually when you want a function to occur at the same time as your program.  If you create server software, you want the server not only listens to one connection but to many connections. In short, threads enable programs to execute multiple tasks at once.

Related Courses:

Python threading

Let’s create a thread program. In this program we will start 10 threads which will each output their id.

import threading
# Our thread class
class MyThread (threading.Thread):
    def __init__(self,x):
        self.__x = x
    def run (self):
          print str(self.__x)
# Start 10 threads.
for x in xrange(10):



Threads do not have to stop if run once. Threads could be timed, where a threads functionality is repeated every x seconds.

Timed threads

In Python, the Timer class is a subclass of the Thread class. This means it behaves similar. We can use the timer class to create timed threads. Timers are started with the .start() method call, just like regular threads. The program below creates a thread that starts after 5 seconds.

#!/usr/bin/env python
from threading import *
def hello():
    print "hello, world"
# create thread
t = Timer(10.0, hello)
# start thread after 10 seconds

Repeating functionality using threads
We can execute threads endlessly like this:

#!/usr/bin/env python
from threading import *
import time
def handleClient1():
        print "Waiting for client 1..."
        time.sleep(5) # wait 5 seconds      
def handleClient2():
        print "Waiting for client 2..."
        time.sleep(5) # wait 5 seconds
# create threads
t = Timer(5.0, handleClient1)
t2 = Timer(3.0, handleClient2)
# start threads


Python Subprocess
Python lambda
This entry was posted in Beginner and tagged , . Bookmark the permalink.

13 Responses to Threading and threads

  1. Ma says:

    I run the first example and get the output “Disallowed system call: SYS_pipe”
    Should the last line “MyThread(x).start()” be changed as “MyThread(x).run()” ?

  2. Kate says:

    When I run the very first example, one or two of the numbers will sometimes be indented when printed out. Sometimes they will just be listed like:
    Do you know what causes this?

    • Frank says:

      Threads do not always execute in chronological order, that causes the listing to be “out of order” sometimes. The indenting is may be something in the thread.

  3. Stewart says:

    I’m getting an Indentation error on the ‘threading.Thread.__init__(self)” line

  4. Bruce says:

    Hi Frank!Thanks for your tutorials.In the last example,there were time.sleep() and Timer().It made me confused.Did it mean wait for 8 seconds or 10 seconds before next thread running?

    • Frank says:

      Hi Bruce! time.sleep() and Timer have a different purpose: time.sleep(x) pauses the program for x seconds. Timer starts a new thread (a parallel process/program).

      In this example we start two Threads: t1 and t2. These are started after 3 and 5 seconds. When we start a thread (parallel program), we don’t want it to be finished directly so we put them in a while loop. In this loop we put some waiting time for each thread with time.sleep(). Without the waiting time, the screen would be filled with the print output.

  5. Yan says:

    When you excute “MyThread(x).start()”, why the function run() will also be excuted?

    • Frank says:

      Hi Yan, this is usual behavior of threads. The class inherits from “threading.Thread”. You can find the source code of threading.Thread here:

      We call the superclass .start() function.
      On line 745 : _start_new_thread(self.__bootstrap, ())
      On line 769 : __bootstrap()
      On line 783 : self.__bootstrap_inner()
      On line 792 : __bootstrap_inner
      On line 810 :

      In summary, it calls run() because the superclass Thread calls that function, which we may redefine when creating a Thread. I hope that helps, let me know if you have any questions.

  6. Tao says:

    In the Timed threads example above, shouldn’t t = Timer(5.0, hello) instead of t = Timer(10.0, hello) in order for it to start thread after 5 seconds? Is it a typo?

  7. Alexander says:

    These tutorials are clear and easy to understand, great job. I’ve got some friends who could use these.