Open germaniuss opened 7 months ago
Hey @germaniuss i would like work on this issue. could you please assign me this issue?
This is interesting because I personally do a lot of async_to_sync(coroutine)()
style code so I probably didn't notice this myself!
PR looks good - one linting issue that needs fixing and I can land it.
This is interesting because I personally do a lot of
async_to_sync(coroutine)()
style code so I probably didn't notice this myself! PR looks good - one linting issue that needs fixing and I can land it.
There is actually one issue I spotted in the PR. In case I run the new decorated function in a thread not started by SyncToAsync
, the AsyncToSync
object would not have self.main_event_loop
initialized, I fixed that issue by moving the check for if there is a running event loop back to __init__
(which made no sense to check in __call__
anyways).
Also fixed the linter issue.
When using a function decorated with
@async_to_sync
inside of a function decorated with@sync_to_async
a new thread is spawned instead of reusing the same thread and event loop. This issue does not happen when doingasync_to_sync(coroutine)()
.This is due to the fact that the AsyncToSync sets
main_event_loop
andmain_event_loop_pid
on__init__
and not on__call__
and SyncToAsync only setsmain_event_loop
andmain_event_loop_pid
on__call__
.The easy way to solve this is moving the initialization of
self.main_event_loop
andself.main_event_loop_pid
from__init__
to__call__
in AsyncToSync (#439 fixes the issue)Consider this example on why this is relevant:
The output is:
In this example calling
async_to_sync
inblocking_func
is a bit akward, therefore our only option is to modify thecallback
method. This however is also akward since we have to create an auxiliary coroutine for it to use the correct thread. The best syntax would be to use the@async_to_sync
decorator that is however not thread safe.