🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The threading.local class in Python's threading module provides a way to manage thread-local data. Each thread that accesses a threading.local instance will have its own independent value for the attributes stored in it. This is useful for storing data that should not be shared between threads.
Table of Contents
- Introduction
threading.localClass Syntax- Examples
- Basic Usage
- Using Thread-Local Data in Functions
- Thread-Local Data in a Class
- Real-World Use Case
- Conclusion
Introduction
The threading.local class allows you to create thread-local data, meaning each thread has its own independent value for the attributes stored in the threading.local instance. This is particularly useful for storing data that should be unique to each thread, such as user session information in a web server.
threading.local Class Syntax
Here is how you create and use a threading.local instance:
import threading
local_data = threading.local()
Examples
Basic Usage
Create and use thread-local data.
Example
import threading
local_data = threading.local()
def worker():
local_data.value = threading.current_thread().name
print(f"{local_data.value} has local value: {local_data.value}")
threads = []
for i in range(5):
thread = threading.Thread(target=worker, name=f"Thread-{i}")
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
Output:
Thread-0 has local value: Thread-0
Thread-1 has local value: Thread-1
Thread-2 has local value: Thread-2
Thread-3 has local value: Thread-3
Thread-4 has local value: Thread-4
Using Thread-Local Data in Functions
Store and retrieve thread-local data within a function.
Example
import threading
local_data = threading.local()
def process_data():
local_data.value = threading.current_thread().name
print(f"{local_data.value} is processing data")
def worker():
process_data()
threads = []
for i in range(3):
thread = threading.Thread(target=worker, name=f"Worker-{i}")
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
Output:
Worker-0 is processing data
Worker-1 is processing data
Worker-2 is processing data
Thread-Local Data in a Class
Use thread-local data within a class.
Example
import threading
class ThreadLocalData:
def __init__(self):
self.local_data = threading.local()
def set_value(self, value):
self.local_data.value = value
def get_value(self):
return getattr(self.local_data, 'value', None)
def worker(local_instance, value):
local_instance.set_value(value)
print(f"{threading.current_thread().name} has value: {local_instance.get_value()}")
local_instance = ThreadLocalData()
threads = []
for i in range(3):
thread = threading.Thread(target=worker, args=(local_instance, f"Value-{i}"), name=f"Thread-{i}")
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
Output:
Thread-0 has value: Value-0
Thread-1 has value: Value-1
Thread-2 has value: Value-2
Real-World Use Case
Storing User Session Data
Use threading.local to store user session data in a web server environment.
Example
import threading
import time
local_data = threading.local()
def process_request(user_id):
local_data.user_id = user_id
print(f"Processing request for user: {local_data.user_id}")
time.sleep(1)
print(f"Finished processing request for user: {local_data.user_id}")
def handle_request(user_id):
process_request(user_id)
threads = []
for user_id in range(5):
thread = threading.Thread(target=handle_request, args=(user_id,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
Output:
Processing request for user: 0
Processing request for user: 1
Processing request for user: 2
Processing request for user: 3
Processing request for user: 4
Finished processing request for user: 0
Finished processing request for user: 1
Finished processing request for user: 2
Finished processing request for user: 3
Finished processing request for user: 4
Conclusion
The threading.local class is used for managing thread-local data in Python. It allows each thread to have its own independent data, preventing interference between threads. This is particularly useful for scenarios where data should not be shared between threads, such as user session data in web servers. Proper usage can enhance the reliability and maintainability of your multithreaded applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment