A Python application runs on a single thread, unless you explicitly enable multithreading.
Why is multithreading useful? Code in Python is ran in sequence, one instruction after another.
If you define a function that sleeps 3 seconds and then prints something, like this:
import time def greet(): time.sleep(3) print('hello') greet() print('world')
world string is printed after 3 seconds, because we call
time.sleep(3) inside the
This is just a silly example, but imagine processing an image, getting a resource from the network, or writing a big file to disk. Anything that can take a lot of time.
With multithreading we can run the function that takes a lot of time into a separate thread, and go on with our program in the meantime.
threading standard library module helps with implementing multithreading. You import
Thread from it:
from threading import Thread
Then we pass the function we must execute as the
target argument to the
Thread() function, getting a thread object:
t = Thread(target=greet)
then we call its start() method to start the thread:
Try running this code:
from threading import Thread import time def greet(): time.sleep(3) print('hello') t = Thread(target=greet) t.start() print('world')
You will now see
world printed 3 seconds before
hello shows up in the console.
The program does not end until the thread (or all the threads it started) end, unless you start a thread as a deamon.
Those are the basics of multithreading. This is complex, and can lead to the introduction of bugs if not done well.
Download my free Python Handbook!