Python Create / Start / Join Threads – Control Concurrency Effectively
Introduction – Why Use Python Threads?
Multithreading in Python enables your programs to run multiple operations concurrently. Whether you’re managing network requests, file I/O, or background tasks like logging or monitoring, threads help keep your application responsive and efficient.
This guide focuses on the three core thread operations:
- Creating a thread
- Starting a thread
- Joining a thread (waiting for completion)
In this guide, you’ll learn:
- How to create threads using
threading.Thread - How to start and run threads concurrently
- How to join threads to the main program
- Examples using both functions and classes
- Best practices for managing thread life
Step 1: Create a Thread with threading.Thread
Import the threading module:
import threading
Example 1 – Using a Function
def task():
print("Thread is running")
t = threading.Thread(target=task)
At this stage, the thread is created but not started. It’s in the “new” state.
Step 2: Start the Thread
Use .start() to schedule the thread for execution:
t.start()
print("Main thread continues")
The thread is now “runnable”, and once the OS schedules it, it becomes “running”.
Step 3: Join the Thread (Wait for Completion)
t.join()
print("Thread has finished")
join() makes the main thread wait until the target thread completes.
Example – Full Workflow
import threading
import time
def background_task():
print("Starting background task...")
time.sleep(2)
print("Background task finished.")
thread = threading.Thread(target=background_task)
thread.start()
print("Main thread is running...")
thread.join()
print("Main thread exits after thread completes.")
Output:
Starting background task...
Main thread is running...
Background task finished.
Main thread exits after thread completes.
Example – Thread with Arguments
def greet(name):
print(f"Hello, {name}!")
t = threading.Thread(target=greet, args=("Alice",))
t.start()
t.join()
args=() passes arguments as a tuple to the function.
Example – Thread via Subclassing
You can also create a thread by subclassing threading.Thread.
class MyThread(threading.Thread):
def run(self):
print("Hello from subclassed thread!")
t = MyThread()
t.start()
t.join()
Recommended when you need to maintain state or extend thread behavior.
️ Multiple Threads Example
def show_number(n):
print(f"Thread {n} starting")
time.sleep(1)
print(f"Thread {n} done")
threads = []
for i in range(3):
t = threading.Thread(target=show_number, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
print("All threads completed")
Use .join() in a loop to wait for all threads.
Best Practices for Start/Join Threads
| Do This | Avoid This |
|---|---|
Use join() to wait for thread finish | Relying on time.sleep() as a timer |
| Handle exceptions inside thread | Crashing thread without try-except |
| Start all threads before joining | Calling join() too early in the loop |
Use args=() for parameter passing | Modifying global variables carelessly |
Summary – Recap & Next Steps
Creating, starting, and joining threads is the foundation of Python multithreading. These steps enable you to run tasks concurrently while maintaining control over program execution.
Key Takeaways:
-
threading.Thread(target=func)creates a thread -
start()schedules the thread for execution -
join()pauses the main thread until the thread finishes - Threads can be created with both functions and class-based approaches
Real-World Relevance:
Used in parallel downloads, non-blocking I/O, background tasks, game loops, and real-time applications.
FAQ – Python Create / Start / Join Threads
What does join() do in Python threads?
It waits for the thread to finish before moving forward.
Can I pass arguments to a thread function?
Yes, use args=(arg1, arg2, ...) in the Thread() constructor.
Is start() the same as run()?
No. start() schedules the thread.
Calling run() manually runs it in the current thread, not in a new thread.
How many times can I start a thread?
Only once. After calling start(), you cannot restart the same thread object.
Should I use join() always?
Yes, if your main thread depends on the result or you need to control flow. Otherwise, threads may outlive the main process.
Share Now :
