sync_to_async does not find root thread inside a task
See original GitHub issueWhen you use create_task
(or any way of making a coroutine not through asgiref), and the root thread is synchronous, then sync_to_async
in thread-sensitive mode will use the root thread outside of tasks and a single, specific new thread inside of tasks, ruining the thread-sensitive guarantee.
Instead, we should make sync_to_async
always first look for an executor on the root thread and, if it finds it, use that to run code.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:11 (3 by maintainers)
Top Results From Across the Web
Querying Django ORM inside celery task ... - Stack Overflow
SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I find it strange that it happens ...
Read more >Understanding Async, Avoiding Deadlocks in C# | by Eke Péter
Task is not thread. Task does not guarantee parallel execution. Task does not belong to a Thread or anything like that.
Read more >async_std::task - Rust - Docs.rs
If a panic occurs inside a task, there is no meaningful way of recovering, so the panic will propagate through any thread boundaries...
Read more >Async Views in Django - TestDriven.io
Simplify basic background tasks with Django's async views; Use sync_to_async to make a synchronous call inside an async view; Explain when you ...
Read more >Common Mistakes Using Python3 asyncio
Compared to C# async/await , the interfaces of Python3 asyncio is verbose and ... If you want to call foo() as an asynchronous...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Thanks. I came up with a cleaner solution that also makes your test case pass: associate a
CurrentThreadExecutor
with each event loop we create, and havesync_to_async
look up thatCurrentThreadExecutor
from the current event loop if it can’t find one from the context.Updated #320.
@andersk here is a repo with as minimal a test case as I can manage with grpc’s boilerplate: https://github.com/yourcelf/grpc-asgiref
Test file is here: https://github.com/yourcelf/grpc-asgiref/blob/main/test_grpc_sync_to_async.py, the rest of the repo is boilerplate to set up the protobuf definition and compiled files for the grpc server to use.
Sadly, https://github.com/django/asgiref/pull/320 does not seem to address the problem – the
@sync_to_async
decorated method executed by the grpc server still runs onThreadPoolExecutor-0_0
instead ofMainThread
with that branch with patchedcreate_task
.