In this tutorial, we will discuss how to start a thread in Python. Threading is a powerful programming concept that allows you to run multiple tasks concurrently.
Python supports various methods to perform threading, and this tutorial will guide you through a simple example of creating and starting threads using the threading module from the Python standard library.
Step 1: Import the threading module
The first step is to import the threading
module, which contains the tools required to manage threads in Python.
1 |
import threading |
Step 2: Define the target function
Next, you need to define the function that you want to execute concurrently using threads. This function will be the target of the threads you create. For example, let’s create a simple print_numbers
function that prints numbers from 1 to 5 with a 1-second delay between each number.
1 2 3 4 5 6 |
import time def print_numbers(): for i in range(1, 6): print(i) time.sleep(1) |
Step 3: Create a thread
Now that you have defined the target function, you can create a thread object by calling the threading.Thread
constructor. Pass the target function as the target
argument.
1 |
number_thread = threading.Thread(target=print_numbers) |
Step 4: Start the thread
Once you have created the thread object, you can start it by calling the start()
method. This will begin the execution of the target function in a new thread.
1 |
number_thread.start() |
Step 5: Manage multiple threads
You can create and start multiple threads to execute multiple instances of the target function concurrently. For example, let’s create and start two threads that both print numbers from 1 to 5.
1 2 3 4 5 6 7 |
# Create two threads number_thread1 = threading.Thread(target=print_numbers) number_thread2 = threading.Thread(target=print_numbers) # Start both threads number_thread1.start() number_thread2.start() |
In this example, two threads will be running concurrently, each printing numbers from 1 to 5.
Full example code
Here’s the full code from this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import threading import time def print_numbers(): for i in range(1, 6): print(i) time.sleep(1) number_thread1 = threading.Thread(target=print_numbers) number_thread2 = threading.Thread(target=print_numbers) number_thread1.start() number_thread2.start() |
Output
The output of the code will look like this:
1 1 2 2 3 3 4 4 5 5
Conclusion
In this tutorial, you learned how to create and start a thread in Python using the threading.Thread
class from the threading
module. You can apply these methods to run multiple tasks concurrently and improve the performance and responsiveness of your Python programs.