π 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 :
