How to Use Threading Module in Python: Simple Guide
Use the
threading module in Python by creating Thread objects with a target function and starting them with start(). Threads run tasks concurrently, allowing your program to do multiple things at once.Syntax
The basic syntax to use the threading module involves importing it, creating a Thread object with a target function, and starting the thread.
- import threading: Loads the threading module.
- threading.Thread(target=func): Creates a thread that will run the function
func. - thread.start(): Starts the thread to run concurrently.
- thread.join(): Waits for the thread to finish before continuing.
python
import threading def worker(): print('Worker thread is running') thread = threading.Thread(target=worker) thread.start() thread.join()
Output
Worker thread is running
Example
This example shows how to run two threads that print messages with a delay. It demonstrates how threads run at the same time, making the program faster for waiting tasks.
python
import threading import time def print_numbers(): for i in range(1, 6): print(f'Number: {i}') time.sleep(1) def print_letters(): for letter in ['A', 'B', 'C', 'D', 'E']: print(f'Letter: {letter}') time.sleep(1) thread1 = threading.Thread(target=print_numbers) thread2 = threading.Thread(target=print_letters) thread1.start() thread2.start() thread1.join() thread2.join() print('Both threads finished')
Output
Number: 1
Letter: A
Number: 2
Letter: B
Number: 3
Letter: C
Number: 4
Letter: D
Number: 5
Letter: E
Both threads finished
Common Pitfalls
Common mistakes when using threading include:
- Not calling
start()on the thread, so the function never runs. - Forgetting
join(), which can cause the main program to exit before threads finish. - Accessing shared data without locks, causing data corruption.
Always use start() to run threads and join() to wait for them. Use threading.Lock() to protect shared data.
python
import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(100000): with lock: counter += 1 threads = [threading.Thread(target=increment) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() print(f'Counter value: {counter}')
Output
Counter value: 200000
Quick Reference
| Method | Description |
|---|---|
| threading.Thread(target=func) | Create a new thread to run func |
| thread.start() | Start the thread's activity |
| thread.join() | Wait for the thread to finish |
| threading.Lock() | Create a lock to protect shared data |
| lock.acquire()/lock.release() | Manually lock and unlock (use with care) |
Key Takeaways
Create threads with threading.Thread and run them with start().
Use join() to wait for threads to finish before continuing.
Protect shared data with threading.Lock to avoid errors.
Threads run functions concurrently, speeding up waiting tasks.
Always start threads; just creating them does not run the code.