[Python] Difference between asyncio call_soon and call_soon_threadsafe? Why is call_soon...

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    Recently I read the code of asyncio and felt confused about loop.call_soon and loop.call_soon_threadsafe. The only difference I found is that there is a _write_to_self in call_soon_threadsafe. As we know, a event loop runs in a specific thread. All tasks scheduled by the event loop orderly. And we can assume tasks are thread safe while they were scheduled one by one. So how can thread unsafe situation happen in call_soon?

    call_soon call_soon_threadsafe
    self._check_closed() self._check_closed()
    if self._debug: if self._debug:
    self._check_thread()
    self._check_callback(callback, 'call_soon') self._check_callback(callback, 'call_soon_threadsafe')
    handle = self._call_soon(callback, args, context) handle = self._call_soon(callback, args, context)
    if handle._source_traceback: if handle._source_traceback:
    del handle._source_traceback[-1] del handle._source_traceback[-1]
    self._write_to_self()
    return handle return handle

    Continue reading...

Compartilhe esta Página