python logo

python threading


Python hosting: Host, run, and code Python in the cloud!

In Python, threads can be effortlessly created using the thread module in Python 2.x and the _thread module in Python 3.x. For a more convenient interaction, the threading module is preferred.
Threads differ from conventional processes in various ways. For instance:

  • Threads exist within a process, acting as a subset.
  • All threads within a process share the same memory and resources.
  • In contrast, different processes have separate memory address spaces.

You might wonder, when is threading useful? Well, consider scenarios where you need simultaneous executions. For instance, if you’re developing server software, it should ideally handle multiple connections simultaneously rather than just one. Essentially, threading enables concurrency, letting programs manage multiple tasks at once.

Related Course:

Python Threading in Practice

Let’s delve into a practical example. We’ll create a program that initiates 10 threads, with each one displaying its unique ID.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import threading

# Defining our thread class
class MyThread(threading.Thread):
def __init__(self, x):
self.__x = x
threading.Thread.__init__(self)

def run(self):
print(str(self.__x))

# Initiating 10 threads
for x in range(10):
MyThread(x).start()

Output:

1
2
3
4
0
1
...
9

A point to note is that threads aren’t restricted to a single execution. You can configure threads to operate on a timer, enabling them to execute their functionality after set intervals.

Delving into Timed Threads

Python offers the Timer class, which is essentially a subclass of the Thread class. This means its functionality is quite similar. With the timer class, we can craft threads that start after a specified duration. For instance, the subsequent program initializes a thread that kicks off after a delay of 5 seconds.

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
from threading import Timer

def hello():
print("hello, world")

# Defining the thread
t = Timer(10.0, hello)

# Launching the thread after a 10-second delay
t.start()

Continuous Execution with Threads

If you need threads to execute repeatedly, here’s how you can accomplish that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
from threading import Timer
import time

def handleClient1():
while True:
print("Waiting for client 1...")
time.sleep(5) # Pausing for 5 seconds

def handleClient2():
while True:
print("Waiting for client 2...")
time.sleep(5) # Pausing for 5 seconds

# Thread definitions
t = Timer(5.0, handleClient1)
t2 = Timer(3.0, handleClient2)

# Starting the threads
t.start()
t2.start()

Threading, when applied correctly, can significantly boost the efficiency and responsiveness of your Python programs.






Leave a Reply:




Alexander Tue, 07 Jul 2015

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

Frank Tue, 07 Jul 2015

Thanks Alexander! I will write more tutorials on this site. Stay tuned

Tao Wed, 08 Jul 2015

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?

Frank Wed, 08 Jul 2015

Hi Tao, yes this is a typo. Thanks! I will update it

Yan Wed, 19 Aug 2015

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

Frank Wed, 19 Aug 2015

Hi Yan, this is usual behavior of threads. The class inherits from "threading.Thread". You can find the source code of threading.Thread here: https://hg.python.org/cpython/file/2.7/Lib/threading.py

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 : self.run()

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.

Bruce Thu, 20 Aug 2015

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 Thu, 20 Aug 2015

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.

Stewart Mon, 12 Oct 2015

I'm getting an Indentation error on the 'threading.Thread.__init__(self)" line

Frank Sat, 17 Oct 2015

Hi stewart, make sure to use spaces instead of tabs. The threading.Thread call needs eight spaces.

Kate Wed, 11 May 2016

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 Sat, 14 May 2016

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.

Ma Thu, 07 Jul 2016

Hi,Frank
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()" ?