Skip to content

Commit

Permalink
Copy context when submission
Browse files Browse the repository at this point in the history
  • Loading branch information
mosquito committed Mar 7, 2024
1 parent fcb26e2 commit 16bae46
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions aiomisc/thread_pool.py
Expand Up @@ -32,6 +32,10 @@ def context_partial(
func: F, *args: Any,
**kwargs: Any,
) -> Any:
warnings.warn(
"context_partial has been deprecated and will be removed",
DeprecationWarning,
)
context = contextvars.copy_context()
return partial(context.run, func, *args, **kwargs)

Expand All @@ -47,6 +51,7 @@ class WorkItemBase:
kwargs: Dict[str, Any]
future: asyncio.Future
loop: asyncio.AbstractEventLoop
context: contextvars.Context


class ThreadPoolStatistic(Statistic):
Expand Down Expand Up @@ -76,10 +81,11 @@ def __call__(self, statistic: ThreadPoolStatistic) -> None:
return

result, exception = None, None

delta = -time.monotonic()
try:
result = self.func(*self.args, **self.kwargs)
result = self.context.run(
self.func, *self.args, **self.kwargs,
)
statistic.success += 1
except BaseException as e:
statistic.error += 1
Expand Down Expand Up @@ -195,6 +201,7 @@ def submit( # type: ignore
args=args,
kwargs=kwargs,
future=future,
context=contextvars.copy_context(),
loop=loop,
),
)
Expand Down Expand Up @@ -232,7 +239,7 @@ def run_in_executor(
try:
loop = asyncio.get_running_loop()
return loop.run_in_executor(
executor, context_partial(func, *args, **kwargs),
executor, partial(func, *args, **kwargs),
)
except RuntimeError:
# In case the event loop is not running right now is
Expand Down

0 comments on commit 16bae46

Please sign in to comment.