liveBook · Manning

Call_soon_threadsafe

As explained in Python Concurrency with asyncio

call_soon_threadsafe is an asyncio event-loop method that schedules a regular callback from another thread for execution on the loop thread.

call_soon_threadsafe schedules a regular Python function on an asyncio event loop from another thread without blocking. It is useful when a thread must safely request work from the loop thread. section 7.4.2

Use it with these distinctions in mind:

  • Pass a regular function, not a coroutine; the callback runs on the next iteration of the event loop. section 7.4.2
  • Use asyncio.run_coroutine_threadsafe for a coroutine; it immediately returns a concurrent.futures Future. section 7.4.2
  • Avoid asyncio.run from a UI thread because it blocks until completion and can hang the application. section 7.4.2

Updating a threaded UI workflow

A Tkinter application can use a callback to request progress updates while an asyncio event loop runs in a separate thread. call_soon_threadsafe safely schedules the regular update function on that loop. section 7.4.2

Figure 7.5 The tk event loop submits a task to the asyncio event loop, which runs in a separate thread.
07-05

The event-loop diagram clarifies how a Tkinter loop submits work to an asyncio loop running in another thread. section 7.4.2

How Python Concurrency with asyncio covers it

How deep it goes
Defines the callback-versus-coroutine distinction and timing, but defers implementation internals.
Examples
Uses a Tkinter URL stress tester with progress callbacks and a separately threaded asyncio event loop.
What it assumes
Assumes basic Python functions, threads, Tkinter, and asyncio event loops while distinguishing coroutine submission from callback scheduling.
What you can do after
Operate/configure it to submit non-blocking callbacks safely from a separate application thread.
How it connects
Connects asyncio event loops, threads, coroutines, Tkinter, and concurrent.futures Future objects.

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.