Creating Threads in Python: A Quick Guide
Q: How can you create a thread in Python? Can you provide a simple example?
- Multithreading and Multiprocessing in Python
- Junior level question
Explore all the latest Multithreading and Multiprocessing in Python interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Multithreading and Multiprocessing in Python interview for FREE!
In Python, you can create a thread using the `threading` module, which is part of the standard library. The simplest way to create a thread is to define a function that contains the code you want to run in the thread and then instantiate a `Thread` object with this function.
Here’s a simple example:
```python
import threading
import time
# Function to be executed in thread
def print_numbers():
for i in range(5):
print(i)
time.sleep(1)
# Creating a thread
number_thread = threading.Thread(target=print_numbers)
# Starting the thread
number_thread.start()
# Main thread continues to run independently
for i in range(5, 10):
print(i)
time.sleep(1)
# Wait for the number_thread to finish
number_thread.join()
```
In this example, `print_numbers` is the function that will be executed by the new thread. We create a thread `number_thread`, point it to the `print_numbers` function, and start it with `number_thread.start()`. This will run `print_numbers` concurrently with the main thread, which is printing numbers from 5 to 9. Finally, `number_thread.join()` is called to ensure that the main thread waits for `number_thread` to finish before it exits.
Using threads can be particularly useful for I/O-bound operations where you can perform multiple tasks simultaneously without blocking the main program's execution.
Here’s a simple example:
```python
import threading
import time
# Function to be executed in thread
def print_numbers():
for i in range(5):
print(i)
time.sleep(1)
# Creating a thread
number_thread = threading.Thread(target=print_numbers)
# Starting the thread
number_thread.start()
# Main thread continues to run independently
for i in range(5, 10):
print(i)
time.sleep(1)
# Wait for the number_thread to finish
number_thread.join()
```
In this example, `print_numbers` is the function that will be executed by the new thread. We create a thread `number_thread`, point it to the `print_numbers` function, and start it with `number_thread.start()`. This will run `print_numbers` concurrently with the main thread, which is printing numbers from 5 to 9. Finally, `number_thread.join()` is called to ensure that the main thread waits for `number_thread` to finish before it exits.
Using threads can be particularly useful for I/O-bound operations where you can perform multiple tasks simultaneously without blocking the main program's execution.


