Introduction
The threading
module in Python provides a high-level interface to create and manage threads, enabling you to run code concurrently. This can be especially useful for tasks that can be executed in parallel, such as I/O-bound operations. Below is a list of commonly used methods and functions in the threading
module, with brief examples.
1. Thread()
The Thread
class is the heart of the threading
module. You can create and start new threads using this class.
import threading
def print_numbers():
for i in range(5):
print(i)
t = threading.Thread(target=print_numbers)
t.start() # Starts a new thread
t.join() # Waits for the thread to finish
2. start()
Starts the thread's activity.
t = threading.Thread(target=print_numbers)
t.start() # Runs the target function in a separate thread
3. join([timeout])
Blocks the calling thread until the thread whose join()
method is called terminates. Optionally, you can specify a timeout.
t = threading.Thread(target=print_numbers)
t.start()
t.join(2) # Waits up to 2 seconds for the thread to finish
4. is_alive()
Returns True
if the thread is still running.
t = threading.Thread(target=print_numbers)
t.start()
print(t.is_alive()) # True if the thread is still running
5. current_thread()
Returns the current Thread
object, representing the calling thread.
import threading
def print_current_thread():
print(threading.current_thread())
t = threading.Thread(target=print_current_thread)
t.start() # Prints the current thread info
6. enumerate()
Returns a list of all Thread
objects currently alive.
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_numbers)
t1.start()
t2.start()
print(threading.enumerate()) # Lists all active threads
7. active_count()
Returns the number of Thread
objects currently alive.
print(threading.active_count()) # Returns the number of active threads
8. Lock()
A Lock
object is a primitive lock that is used to prevent race conditions. You can use it to ensure only one thread accesses a shared resource at a time.
lock = threading.Lock()
def thread_safe_function():
with lock: # Acquires the lock
# Critical section
print("Thread-safe code")
t = threading.Thread(target=thread_safe_function)
t.start()
9. RLock()
A reentrant lock allows a thread to acquire()
the lock multiple times without blocking itself.
lock = threading.RLock()
def reentrant_function():
with lock:
with lock: # Same thread can acquire the lock again
print("Reentrant lock example")
t = threading.Thread(target=reentrant_function)
t.start()
10. Condition()
A Condition
object allows threads to wait for some condition to be met.
condition = threading.Condition()
def thread_wait():
with condition:
condition.wait() # Wait for the condition
print("Condition met")
def thread_notify():
with condition:
condition.notify() # Notify the waiting thread
t1 = threading.Thread(target=thread_wait)
t2 = threading.Thread(target=thread_notify)
t1.start()
t2.start()
11. Event()
An Event
object is used to signal between threads. A thread can wait for an event to be set, and another thread can set the event.
event = threading.Event()
def wait_for_event():
event.wait() # Wait until the event is set
print("Event has been set")
t = threading.Thread(target=wait_for_event)
t.start()
event.set() # Set the event to allow the thread to continue
12. Semaphore()
A Semaphore
object allows you to limit the number of threads that can access a resource simultaneously.
semaphore = threading.Semaphore(2) # Only 2 threads can access the resource at once
def access_resource():
with semaphore:
print("Resource accessed")
t1 = threading.Thread(target=access_resource)
t2 = threading.Thread(target=access_resource)
t3 = threading.Thread(target=access_resource)
t1.start()
t2.start()
t3.start()
13. Timer(interval, function)
A Timer
thread executes a function after a specified interval.
def delayed_function():
print("Executed after delay")
timer = threading.Timer(3, delayed_function)
timer.start() # Executes `delayed_function` after 3 seconds
14. setDaemon(True)
Daemon threads run in the background and exit automatically when the main program exits. You can make a thread a daemon by calling setDaemon(True)
or passing daemon=True
to the Thread
constructor.
t = threading.Thread(target=print_numbers, daemon=True)
t.start() # Daemon thread will exit when the main program ends
Conclusion
The threading
module is a powerful tool for handling concurrency in Python. It provides multiple classes and methods to create and control threads, making it easy to execute code in parallel. From using basic Thread
objects to managing synchronization with Lock
and Semaphore
, this module is essential for writing concurrent Python programs.
Top comments (0)