In the previous lesson, we saw what a thread is. Now let’s see how we can speed up our Python programs with the
To review, a thread is a unique flow of execution. Theoretically, multiple threads mean the ability to run multiple things at the same time. However, in Python, threads do not actually run simultaneously; they merely appear to do so. Still, we will find that threading can increase the speed of our program. Generally, threading will perform much better than sequential programming if tasks within your program spend a lot of time waiting for external events to occur.
To create a thread instance in Python, we use the following code:
import threading example_thread = threading.Thread(target=some_function, args=(some_arg,))
The two main parameters we will focus on are:
target: this is the function you want to execute with thread(s). It defaults to
args: this is the argument or set of arguments applied to the target function. It is a tuple and defaults to
For example, let’s say we wanted to apply a thread to the function called
analyze_list() with arguments
l1, l2, l3. We would use the following code:
t = threading.Thread(target=analyze_list, args=(l1, l2, l3))
After creating our thread instance, we also have to “start” our thread using
.start(). Therefore, to make sure
t executes on Run, we write:
Let’s practice with an example!
Let’s apply a thread to the sequential example from our previous exercise. In script.py, we have a function called
To start, call
'Codecademy' as the input. Inside the terminal, type
python3 script.py and press Enter. To check your answer, click Check Work once your program finishes running.
How long does the code take to execute?
Let’s try running
greeting_with_sleep() with a single thread.
Create a thread object called
t. This thread should execute
'Codecademy' as the argument.
Inside the terminal, type
python3 script.py and press Enter. To check your answer, click Check Work once your program finishes running. Does the program run faster now? What do you think is happening?