Logo

dev-resources.site

for different kinds of informations.

A Quick Guide to the Python threading Module with Examples

Published at
9/12/2024
Categories
programming
python
threading
Author
usooldatascience
Categories
3 categories in total
programming
open
python
open
threading
open
Author
16 person written this
usooldatascience
open
A Quick Guide to the Python threading Module with Examples

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
Enter fullscreen mode Exit fullscreen mode

2. start()

Starts the thread's activity.

t = threading.Thread(target=print_numbers)
t.start()  # Runs the target function in a separate thread
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

7. active_count()

Returns the number of Thread objects currently alive.

print(threading.active_count())  # Returns the number of active threads
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

threading Article's
30 articles in total
Favicon
Concorrência e paralelismo em Python
Favicon
Navigating Concurrency for Large-Scale Systems
Favicon
Common Java Developer Interview Questions and Answers on multithreading, garbage collection, thread pools, and synchronization
Favicon
Real-time plotting with pyplot
Favicon
A Quick Guide to the Python threading Module with Examples
Favicon
Understanding Threading and Multiprocessing in Python: A Comprehensive Guide
Favicon
I Asked Copilot to Explain Threading in Python to a Dog
Favicon
Introduction to GCD (Grand Central Dispatch)
Favicon
Achieving multi-threading by creating threads manually in Swift
Favicon
Swift Concurrency
Favicon
Python Multithreading: Unlocking Concurrency for Better Performance
Favicon
Choosing the best asynchronous library in Python
Favicon
Two Lines of Code Eluded me for Several Months
Favicon
A Comprehensive Guide to Python Threading: Advanced Concepts and Best Practices
Favicon
Thread synchronisation
Favicon
Rust Learning Note: Multithreading
Favicon
Async vs Threading vs Multiprocessing in Python
Favicon
02.Android Background Task
Favicon
How to handle threads with multiple gunicorn workers to get consistent result
Favicon
Tasks, BackgroundWorkers, and Threads
Favicon
Understanding Task.WhenAll in C#
Favicon
Producer/consumer pipelines with System.Threading.Channels
Favicon
How to auto-refresh Realm inside Android WorkManager
Favicon
Understanding Task in .Net
Favicon
Como resolvemos um bug que afetava 3000 usuários e nos custaria milhões por ano
Favicon
Java Thread Programming (Part 1)
Favicon
So, you want to launch several threads in Python and something does not work?
Favicon
Higher level threading in C++
Favicon
Solve the scenario - using Thread synchronization in Dotnet - CountDownEvent
Favicon
Что в процессе тебе моем?

Featured ones: