Skip to content

Commit

Permalink
removes contextvar behaviour from local when thread_critical=True
Browse files Browse the repository at this point in the history
  • Loading branch information
jthorniley committed Apr 4, 2023
1 parent 5717cc3 commit 98c3140
Showing 1 changed file with 3 additions and 5 deletions.
8 changes: 3 additions & 5 deletions asgiref/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ class Local:
happens when the thread is spawned by `async_to_sync`. If
`thread_critical` is set to `True`, the data will always be thread-local
and will not be transferred to new threads even when using `async_to_sync`.
In other words, when `thread_critical` is `True`, this is a thin wrapper
around `threading.local`.
Unlike plain `contextvars` objects, this utility is threadsafe.
"""
Expand All @@ -86,14 +88,10 @@ def __init__(self, thread_critical: bool = False) -> None:
def _lock_storage(self):
# Thread safe access to storage
if self._thread_critical:
# Ensure context exists in the current thread
if not hasattr(self._storage, "cvar"):
self._storage.cvar = _CVar()

# self._storage is a thread local, so the members
# can't be accessed in another thread (we don't
# need any locks)
yield self._storage.cvar
yield self._storage
else:
# Lock for thread_critical=False as other threads
# can access the exact same storage object
Expand Down

0 comments on commit 98c3140

Please sign in to comment.