Back
+15 XP
Concept

Thread Local Storage with threading.local()

`threading.local()` provides thread-isolated attributes. Changes made to a thread-local object in one thread are completely invisible to all other threads 👤.

python
import threading

session = threading.local()

def worker(user_id):
    session.user = user_id  # Isolated per thread!
    print(f"Thread sees user: {session.user} 👤")

t1 = threading.Thread(target=worker, args=("Alice",))
t2 = threading.Thread(target=worker, args=("Bob",))
t1.start(); t2.start()
t1.join(); t2.join()

# 58. Thread Local Storage with threading.local() `threading.local()` provides thread-isolated attributes. Changes made to a thread-local object in one thread are completely invisible to all other threads 👤. ```python import threading session = threading.local() def worker(user_id): session.user = user_id # Isolated per thread! print(f"Thread sees user: {session.user} 👤") t1 = threading.Thread(target=worker, args=("Alice",)) t2 = threading.Thread(target=worker, args=("Bob",)) t1.start(); t2.start() t1.join(); t2.join() ``` Thread-local data avoids having to pass request context or database connections through every single helper function in a multi-threaded web server! 👤 --- ### Question What happens if Thread-A writes `data.val = 100` on a `threading.local()` object? 🧠 - [ ] a. Thread-B will not see `data.val`; each thread maintains its own private dictionary 👤 - [ ] b. Thread-B will read 100 because memory is shared - [ ] c. Python raises a ThreadSecurityException - [ ] d. The variable is mirrored across all OS user accounts --- ### Challenge Import `threading`. Create `store = threading.local()`. Assign `store.token = 'SECRET_99'`. Print `store.token`. 🎯 <details> <summary>Solution</summary> ```python import threading store = threading.local() store.token = "SECRET_99" print(store.token) ``` </details>

Checkpoint

What happens if Thread-A writes `data.val = 100` on a `threading.local()` object? 🧠

Practice

Import `threading`. Create `store = threading.local()`. Assign `store.token = 'SECRET_99'`. Print `store.token`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks