| 1 |
========================================================= |
| 2 |
Introspecting and extending Trio with ``trio.lowlevel`` |
| 3 |
========================================================= |
| 4 |
|
| 5 |
.. module:: trio.lowlevel |
| 6 |
|
| 7 |
:mod:`trio.lowlevel` contains low-level APIs for introspecting and |
| 8 |
extending Trio. If you're writing ordinary, everyday code, then you |
| 9 |
can ignore this module completely. But sometimes you need something a |
| 10 |
bit lower level. Here are some examples of situations where you should |
| 11 |
reach for :mod:`trio.lowlevel`: |
| 12 |
|
| 13 |
* You want to implement a new :ref:`synchronization primitive |
| 14 |
<synchronization>` that Trio doesn't (yet) provide, like a |
| 15 |
reader-writer lock. |
| 16 |
* You want to extract low-level metrics to monitor the health of your |
| 17 |
application. |
| 18 |
* You want to use a low-level operating system interface that Trio |
| 19 |
doesn't (yet) provide its own wrappers for, like watching a |
| 20 |
filesystem directory for changes. |
| 21 |
* You want to implement an interface for calling between Trio and |
| 22 |
another event loop within the same process. |
| 23 |
* You're writing a debugger and want to visualize Trio's task tree. |
| 24 |
* You need to interoperate with a C library whose API exposes raw file |
| 25 |
descriptors. |
| 26 |
|
| 27 |
You don't need to be scared of :mod:`trio.lowlevel`, as long as you |
| 28 |
take proper precautions. These are real public APIs, with strictly |
| 29 |
defined and carefully documented semantics. They're the same tools we |
| 30 |
use to implement all the nice high-level APIs in the :mod:`trio` |
| 31 |
namespace. But, be careful. Some of those strict semantics have `nasty |
| 32 |
big pointy teeth |
| 33 |
<https://en.wikipedia.org/wiki/Rabbit_of_Caerbannog>`__. If you make a |
| 34 |
mistake, Trio may not be able to handle it gracefully; conventions and |
| 35 |
guarantees that are followed strictly in the rest of Trio do not |
| 36 |
always apply. When you use this module, it's your job to think about |
| 37 |
how you're going to handle the tricky cases so you can expose a |
| 38 |
friendly Trio-style API to your users. |
| 39 |
|
| 40 |
|
| 41 |
Debugging and instrumentation |
| 42 |
============================= |
| 43 |
|
| 44 |
Trio tries hard to provide useful hooks for debugging and |
| 45 |
instrumentation. Some are documented above (the nursery introspection |
| 46 |
attributes, :meth:`trio.Lock.statistics`, etc.). Here are some more. |
| 47 |
|
| 48 |
|
| 49 |
Global statistics |
| 50 |
----------------- |
| 51 |
|
| 52 |
.. function:: current_statistics() -> RunStatistics |
| 53 |
|
| 54 |
Returns an object containing run-loop-level debugging information: |
| 55 |
|
| 56 |
.. autoclass:: RunStatistics() |
| 57 |
|
| 58 |
|
| 59 |
.. _trio_contexts: |
| 60 |
|
| 61 |
Checking for Trio |
| 62 |
----------------- |
| 63 |
|
| 64 |
If you want to interact with an active Trio run -- perhaps you need to |
| 65 |
know the :func:`~trio.current_time` or the |
| 66 |
:func:`~trio.lowlevel.current_task` -- then Trio needs to have certain |
| 67 |
state available to it or else you will get a |
| 68 |
``RuntimeError("must be called from async context")``. |
| 69 |
This requires that you either be: |
| 70 |
|
| 71 |
* indirectly inside (and on the same thread as) a call to |
| 72 |
:func:`trio.run`, for run-level information such as the |
| 73 |
:func:`~trio.current_time` or :func:`~trio.lowlevel.current_clock`; |
| 74 |
or |
| 75 |
|
| 76 |
* indirectly inside a Trio task, for task-level information such as |
| 77 |
the :func:`~trio.lowlevel.current_task` or |
| 78 |
:func:`~trio.current_effective_deadline`. |
| 79 |
|
| 80 |
Internally, this state is provided by thread-local variables tracking |
| 81 |
the current run and the current task. Sometimes, it's useful to know |
| 82 |
in advance whether a call will fail or to have dynamic information for |
| 83 |
safeguards against running something inside or outside Trio. To do so, |
| 84 |
call :func:`trio.lowlevel.in_trio_run` or |
| 85 |
:func:`trio.lowlevel.in_trio_task`, which will provide answers |
| 86 |
according to the following table. |
| 87 |
|
| 88 |
|
| 89 |
+--------------------------------------------------------+-----------------------------------+------------------------------------+ |
| 90 |
| situation | :func:`trio.lowlevel.in_trio_run` | :func:`trio.lowlevel.in_trio_task` | |
| 91 |
+========================================================+===================================+====================================+ |
| 92 |
| inside a Trio-flavored async function | `True` | `True` | |
| 93 |
+--------------------------------------------------------+-----------------------------------+------------------------------------+ |
| 94 |
| in a thread without an active call to :func:`trio.run` | `False` | `False` | |
| 95 |
+--------------------------------------------------------+-----------------------------------+------------------------------------+ |
| 96 |
| in a guest run's host loop | `True` | `False` | |
| 97 |
+--------------------------------------------------------+-----------------------------------+------------------------------------+ |
| 98 |
| inside an instrument call | `True` | depends | |
| 99 |
+--------------------------------------------------------+-----------------------------------+------------------------------------+ |
| 100 |
| in a thread created by :func:`trio.to_thread.run_sync` | `False` | `False` | |
| 101 |
+--------------------------------------------------------+-----------------------------------+------------------------------------+ |
| 102 |
| inside an abort function | `True` | `True` | |
| 103 |
+--------------------------------------------------------+-----------------------------------+------------------------------------+ |
| 104 |
|
| 105 |
.. autofunction:: in_trio_run |
| 106 |
|
| 107 |
.. autofunction:: in_trio_task |
| 108 |
|
| 109 |
The current clock |
| 110 |
----------------- |
| 111 |
|
| 112 |
.. autofunction:: current_clock |
| 113 |
|
| 114 |
|
| 115 |
.. _instrumentation: |
| 116 |
|
| 117 |
Instrument API |
| 118 |
-------------- |
| 119 |
|
| 120 |
The instrument API provides a standard way to add custom |
| 121 |
instrumentation to the run loop. Want to make a histogram of |
| 122 |
scheduling latencies, log a stack trace of any task that blocks the |
| 123 |
run loop for >50 ms, or measure what percentage of your process's |
| 124 |
running time is spent waiting for I/O? This is the place. |
| 125 |
|
| 126 |
The general idea is that at any given moment, :func:`trio.run` |
| 127 |
maintains a set of "instruments", which are objects that implement the |
| 128 |
:class:`trio.abc.Instrument` interface. When an interesting event |
| 129 |
happens, it loops over these instruments and notifies them by calling |
| 130 |
an appropriate method. The tutorial has :ref:`a simple example of |
| 131 |
using this for tracing <tutorial-instrument-example>`. |
| 132 |
|
| 133 |
Since this hooks into Trio at a rather low level, you do have to be |
| 134 |
careful. The callbacks are run synchronously, and in many cases if |
| 135 |
they error out then there isn't any plausible way to propagate this |
| 136 |
exception (for instance, we might be deep in the guts of the exception |
| 137 |
propagation machinery...). Therefore our `current strategy |
| 138 |
<https://github.com/python-trio/trio/issues/47>`__ for handling |
| 139 |
exceptions raised by instruments is to (a) log an exception to the |
| 140 |
``"trio.abc.Instrument"`` logger, which by default prints a stack |
| 141 |
trace to standard error and (b) disable the offending instrument. |
| 142 |
|
| 143 |
You can register an initial list of instruments by passing them to |
| 144 |
:func:`trio.run`. :func:`add_instrument` and |
| 145 |
:func:`remove_instrument` let you add and remove instruments at |
| 146 |
runtime. |
| 147 |
|
| 148 |
.. autofunction:: add_instrument |
| 149 |
|
| 150 |
.. autofunction:: remove_instrument |
| 151 |
|
| 152 |
And here's the interface to implement if you want to build your own |
| 153 |
:class:`~trio.abc.Instrument`: |
| 154 |
|
| 155 |
.. autoclass:: trio.abc.Instrument |
| 156 |
:members: |
| 157 |
|
| 158 |
The tutorial has a :ref:`fully-worked example |
| 159 |
<tutorial-instrument-example>` of defining a custom instrument to log |
| 160 |
Trio's internal scheduling decisions. |
| 161 |
|
| 162 |
|
| 163 |
Low-level process spawning |
| 164 |
========================== |
| 165 |
|
| 166 |
.. autofunction:: trio.lowlevel.open_process |
| 167 |
|
| 168 |
|
| 169 |
Low-level I/O primitives |
| 170 |
======================== |
| 171 |
|
| 172 |
Different environments expose different low-level APIs for performing |
| 173 |
async I/O. :mod:`trio.lowlevel` exposes these APIs in a relatively |
| 174 |
direct way, so as to allow maximum power and flexibility for higher |
| 175 |
level code. However, this means that the exact API provided may vary |
| 176 |
depending on what system Trio is running on. |
| 177 |
|
| 178 |
|
| 179 |
Universally available API |
| 180 |
------------------------- |
| 181 |
|
| 182 |
All environments provide the following functions: |
| 183 |
|
| 184 |
.. function:: wait_readable(obj) |
| 185 |
:async: |
| 186 |
|
| 187 |
Block until the kernel reports that the given object is readable. |
| 188 |
|
| 189 |
On Unix systems, ``obj`` must either be an integer file descriptor, |
| 190 |
or else an object with a ``.fileno()`` method which returns an |
| 191 |
integer file descriptor. Any kind of file descriptor can be passed, |
| 192 |
though the exact semantics will depend on your kernel. For example, |
| 193 |
this probably won't do anything useful for on-disk files. |
| 194 |
|
| 195 |
On Windows systems, ``obj`` must either be an integer ``SOCKET`` |
| 196 |
handle, or else an object with a ``.fileno()`` method which returns |
| 197 |
an integer ``SOCKET`` handle. File descriptors aren't supported, |
| 198 |
and neither are handles that refer to anything besides a |
| 199 |
``SOCKET``. |
| 200 |
|
| 201 |
:raises trio.BusyResourceError: |
| 202 |
if another task is already waiting for the given socket to |
| 203 |
become readable. |
| 204 |
:raises trio.ClosedResourceError: |
| 205 |
if another task calls :func:`notify_closing` while this |
| 206 |
function is still working. |
| 207 |
|
| 208 |
.. function:: wait_writable(obj) |
| 209 |
:async: |
| 210 |
|
| 211 |
Block until the kernel reports that the given object is writable. |
| 212 |
|
| 213 |
See `wait_readable` for the definition of ``obj``. |
| 214 |
|
| 215 |
:raises trio.BusyResourceError: |
| 216 |
if another task is already waiting for the given socket to |
| 217 |
become writable. |
| 218 |
:raises trio.ClosedResourceError: |
| 219 |
if another task calls :func:`notify_closing` while this |
| 220 |
function is still working. |
| 221 |
|
| 222 |
|
| 223 |
.. function:: notify_closing(obj) |
| 224 |
|
| 225 |
Call this before closing a file descriptor (on Unix) or socket (on |
| 226 |
Windows). This will cause any `wait_readable` or `wait_writable` |
| 227 |
calls on the given object to immediately wake up and raise |
| 228 |
`~trio.ClosedResourceError`. |
| 229 |
|
| 230 |
This doesn't actually close the object – you still have to do that |
| 231 |
yourself afterwards. Also, you want to be careful to make sure no |
| 232 |
new tasks start waiting on the object in between when you call this |
| 233 |
and when it's actually closed. So to close something properly, you |
| 234 |
usually want to do these steps in order: |
| 235 |
|
| 236 |
1. Explicitly mark the object as closed, so that any new attempts |
| 237 |
to use it will abort before they start. |
| 238 |
2. Call `notify_closing` to wake up any already-existing users. |
| 239 |
3. Actually close the object. |
| 240 |
|
| 241 |
It's also possible to do them in a different order if that's more |
| 242 |
convenient, *but only if* you make sure not to have any checkpoints in |
| 243 |
between the steps. This way they all happen in a single atomic |
| 244 |
step, so other tasks won't be able to tell what order they happened |
| 245 |
in anyway. |
| 246 |
|
| 247 |
|
| 248 |
Unix-specific API |
| 249 |
----------------- |
| 250 |
|
| 251 |
`FdStream` supports wrapping Unix files (such as a pipe or TTY) as |
| 252 |
a stream. |
| 253 |
|
| 254 |
If you have two different file descriptors for sending and receiving, |
| 255 |
and want to bundle them together into a single bidirectional |
| 256 |
`~trio.abc.Stream`, then use `trio.StapledStream`: |
| 257 |
|
| 258 |
.. code-block:: python |
| 259 |
|
| 260 |
bidirectional_stream = trio.StapledStream( |
| 261 |
trio.lowlevel.FdStream(write_fd), |
| 262 |
trio.lowlevel.FdStream(read_fd) |
| 263 |
) |
| 264 |
|
| 265 |
.. autoclass:: FdStream |
| 266 |
:show-inheritance: |
| 267 |
:members: |
| 268 |
|
| 269 |
|
| 270 |
Kqueue-specific API |
| 271 |
------------------- |
| 272 |
|
| 273 |
TODO: these are implemented, but are currently more of a sketch than |
| 274 |
anything real. See `#26 |
| 275 |
<https://github.com/python-trio/trio/issues/26>`__. |
| 276 |
|
| 277 |
.. autofunction:: current_kqueue() |
| 278 |
|
| 279 |
.. autofunction:: wait_kevent(ident, filter, abort_func) |
| 280 |
:async: |
| 281 |
|
| 282 |
.. autofunction:: monitor_kevent(ident, filter) |
| 283 |
:with: queue |
| 284 |
|
| 285 |
|
| 286 |
Windows-specific API |
| 287 |
-------------------- |
| 288 |
|
| 289 |
.. note: this is a function and not `autofunction` since it relies on cffi |
| 290 |
compiling some things. |
| 291 |
|
| 292 |
.. function:: WaitForSingleObject(handle) |
| 293 |
:async: |
| 294 |
|
| 295 |
Async and cancellable variant of `WaitForSingleObject |
| 296 |
<https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx>`__. |
| 297 |
Windows only. |
| 298 |
|
| 299 |
:arg handle: |
| 300 |
A Win32 object handle, as a Python integer. |
| 301 |
:raises OSError: |
| 302 |
If the handle is invalid, e.g. when it is already closed. |
| 303 |
|
| 304 |
|
| 305 |
TODO: these are implemented, but are currently more of a sketch than |
| 306 |
anything real. See `#26 |
| 307 |
<https://github.com/python-trio/trio/issues/26>`__ and `#52 |
| 308 |
<https://github.com/python-trio/trio/issues/52>`__. |
| 309 |
|
| 310 |
.. autofunction:: register_with_iocp(handle) |
| 311 |
|
| 312 |
.. autofunction:: wait_overlapped(handle, lpOverlapped) |
| 313 |
:async: |
| 314 |
|
| 315 |
.. autofunction:: write_overlapped(handle, data) |
| 316 |
:async: |
| 317 |
|
| 318 |
.. autofunction:: readinto_overlapped(handle, data) |
| 319 |
:async: |
| 320 |
|
| 321 |
.. autofunction:: current_iocp() |
| 322 |
|
| 323 |
.. autofunction:: monitor_completion_key() |
| 324 |
:with: queue |
| 325 |
|
| 326 |
|
| 327 |
Global state: system tasks and run-local variables |
| 328 |
================================================== |
| 329 |
|
| 330 |
.. autoclass:: RunVar |
| 331 |
|
| 332 |
.. autofunction:: spawn_system_task |
| 333 |
|
| 334 |
|
| 335 |
Trio tokens |
| 336 |
=========== |
| 337 |
|
| 338 |
.. autoclass:: TrioToken() |
| 339 |
:members: |
| 340 |
|
| 341 |
.. autofunction:: current_trio_token |
| 342 |
|
| 343 |
|
| 344 |
Spawning threads |
| 345 |
================ |
| 346 |
|
| 347 |
.. autofunction:: start_thread_soon |
| 348 |
|
| 349 |
|
| 350 |
Safer KeyboardInterrupt handling |
| 351 |
================================ |
| 352 |
|
| 353 |
Trio's handling of control-C is designed to balance usability and |
| 354 |
safety. On the one hand, there are sensitive regions (like the core |
| 355 |
scheduling loop) where it's simply impossible to handle arbitrary |
| 356 |
:exc:`KeyboardInterrupt` exceptions while maintaining our core |
| 357 |
correctness invariants. On the other, if the user accidentally writes |
| 358 |
an infinite loop, we do want to be able to break out of that. Our |
| 359 |
solution is to install a default signal handler which checks whether |
| 360 |
it's safe to raise :exc:`KeyboardInterrupt` at the place where the |
| 361 |
signal is received. If so, then we do; otherwise, we schedule a |
| 362 |
:exc:`KeyboardInterrupt` to be delivered to the main task at the next |
| 363 |
available opportunity (similar to how :exc:`~trio.Cancelled` is |
| 364 |
delivered). |
| 365 |
|
| 366 |
So that's great, but – how do we know whether we're in one of the |
| 367 |
sensitive parts of the program or not? |
| 368 |
|
| 369 |
This is determined on a function-by-function basis. By default: |
| 370 |
|
| 371 |
- The top-level function in regular user tasks is unprotected. |
| 372 |
- The top-level function in system tasks is protected. |
| 373 |
- If a function doesn't specify otherwise, then it inherits the |
| 374 |
protection state of its caller. |
| 375 |
|
| 376 |
This means you only need to override the defaults at places where you |
| 377 |
transition from protected code to unprotected code or vice-versa. |
| 378 |
|
| 379 |
These transitions are accomplished using two function decorators: |
| 380 |
|
| 381 |
.. function:: disable_ki_protection() |
| 382 |
:decorator: |
| 383 |
|
| 384 |
Decorator that marks the given regular function, generator |
| 385 |
function, async function, or async generator function as |
| 386 |
unprotected against :exc:`KeyboardInterrupt`, i.e., the code inside |
| 387 |
this function *can* be rudely interrupted by |
| 388 |
:exc:`KeyboardInterrupt` at any moment. |
| 389 |
|
| 390 |
If you have multiple decorators on the same function, then this |
| 391 |
should be at the bottom of the stack (closest to the actual |
| 392 |
function). |
| 393 |
|
| 394 |
An example of where you'd use this is in implementing something |
| 395 |
like :func:`trio.from_thread.run`, which uses |
| 396 |
:meth:`TrioToken.run_sync_soon` to get into the Trio |
| 397 |
thread. :meth:`~TrioToken.run_sync_soon` callbacks are run with |
| 398 |
:exc:`KeyboardInterrupt` protection enabled, and |
| 399 |
:func:`trio.from_thread.run` takes advantage of this to safely set up |
| 400 |
the machinery for sending a response back to the original thread, but |
| 401 |
then uses :func:`disable_ki_protection` when entering the |
| 402 |
user-provided function. |
| 403 |
|
| 404 |
.. function:: enable_ki_protection() |
| 405 |
:decorator: |
| 406 |
|
| 407 |
Decorator that marks the given regular function, generator |
| 408 |
function, async function, or async generator function as protected |
| 409 |
against :exc:`KeyboardInterrupt`, i.e., the code inside this |
| 410 |
function *won't* be rudely interrupted by |
| 411 |
:exc:`KeyboardInterrupt`. (Though if it contains any |
| 412 |
:ref:`checkpoints <checkpoints>`, then it can still receive |
| 413 |
:exc:`KeyboardInterrupt` at those. This is considered a polite |
| 414 |
interruption.) |
| 415 |
|
| 416 |
.. warning:: |
| 417 |
|
| 418 |
Be very careful to only use this decorator on functions that you |
| 419 |
know will either exit in bounded time, or else pass through a |
| 420 |
checkpoint regularly. (Of course all of your functions should |
| 421 |
have this property, but if you mess it up here then you won't |
| 422 |
even be able to use control-C to escape!) |
| 423 |
|
| 424 |
If you have multiple decorators on the same function, then this |
| 425 |
should be at the bottom of the stack (closest to the actual |
| 426 |
function). |
| 427 |
|
| 428 |
An example of where you'd use this is on the ``__exit__`` |
| 429 |
implementation for something like a :class:`~trio.Lock`, where a |
| 430 |
poorly-timed :exc:`KeyboardInterrupt` could leave the lock in an |
| 431 |
inconsistent state and cause a deadlock. |
| 432 |
|
| 433 |
Since KeyboardInterrupt protection is tracked per code object, any attempt to |
| 434 |
conditionally protect the same block of code in different ways is unlikely to behave |
| 435 |
how you expect. If you try to conditionally protect a closure, it will be |
| 436 |
unconditionally protected instead:: |
| 437 |
|
| 438 |
def example(protect: bool) -> bool: |
| 439 |
def inner() -> bool: |
| 440 |
return trio.lowlevel.currently_ki_protected() |
| 441 |
if protect: |
| 442 |
inner = trio.lowlevel.enable_ki_protection(inner) |
| 443 |
return inner() |
| 444 |
|
| 445 |
async def amain(): |
| 446 |
assert example(False) == False |
| 447 |
assert example(True) == True # once protected ... |
| 448 |
assert example(False) == True # ... always protected |
| 449 |
|
| 450 |
trio.run(amain) |
| 451 |
|
| 452 |
If you really need conditional protection, you can achieve it by giving each |
| 453 |
KI-protected instance of the closure its own code object:: |
| 454 |
|
| 455 |
def example(protect: bool) -> bool: |
| 456 |
def inner() -> bool: |
| 457 |
return trio.lowlevel.currently_ki_protected() |
| 458 |
if protect: |
| 459 |
inner.__code__ = inner.__code__.replace() |
| 460 |
inner = trio.lowlevel.enable_ki_protection(inner) |
| 461 |
return inner() |
| 462 |
|
| 463 |
async def amain(): |
| 464 |
assert example(False) == False |
| 465 |
assert example(True) == True |
| 466 |
assert example(False) == False |
| 467 |
|
| 468 |
trio.run(amain) |
| 469 |
|
| 470 |
(This isn't done by default because it carries some memory overhead and reduces |
| 471 |
the potential for specializing optimizations in recent versions of CPython.) |
| 472 |
|
| 473 |
.. autofunction:: currently_ki_protected |
| 474 |
|
| 475 |
|
| 476 |
Sleeping and waking |
| 477 |
=================== |
| 478 |
|
| 479 |
Wait queue abstraction |
| 480 |
---------------------- |
| 481 |
|
| 482 |
.. autoclass:: ParkingLot |
| 483 |
:members: |
| 484 |
:undoc-members: |
| 485 |
|
| 486 |
.. autoclass:: ParkingLotStatistics |
| 487 |
:members: |
| 488 |
|
| 489 |
.. autofunction:: add_parking_lot_breaker |
| 490 |
|
| 491 |
.. autofunction:: remove_parking_lot_breaker |
| 492 |
|
| 493 |
Low-level checkpoint functions |
| 494 |
------------------------------ |
| 495 |
|
| 496 |
.. autofunction:: checkpoint |
| 497 |
|
| 498 |
The next two functions are used *together* to make up a checkpoint: |
| 499 |
|
| 500 |
.. autofunction:: checkpoint_if_cancelled |
| 501 |
.. autofunction:: cancel_shielded_checkpoint |
| 502 |
|
| 503 |
These are commonly used in cases where you have an operation that |
| 504 |
might-or-might-not block, and you want to implement Trio's standard |
| 505 |
checkpoint semantics. Example: |
| 506 |
|
| 507 |
.. code-block:: python |
| 508 |
|
| 509 |
async def operation_that_maybe_blocks(): |
| 510 |
await checkpoint_if_cancelled() |
| 511 |
try: |
| 512 |
ret = attempt_operation() |
| 513 |
except BlockingIOError: |
| 514 |
# need to block and then retry, which we do below |
| 515 |
pass |
| 516 |
else: |
| 517 |
# operation succeeded, finish the checkpoint then return |
| 518 |
await cancel_shielded_checkpoint() |
| 519 |
return ret |
| 520 |
while True: |
| 521 |
await wait_for_operation_to_be_ready() |
| 522 |
try: |
| 523 |
return attempt_operation() |
| 524 |
except BlockingIOError: |
| 525 |
pass |
| 526 |
|
| 527 |
This logic is a bit convoluted, but accomplishes all of the following: |
| 528 |
|
| 529 |
* Every successful execution path passes through a checkpoint (assuming that |
| 530 |
``wait_for_operation_to_be_ready`` is an unconditional checkpoint) |
| 531 |
|
| 532 |
* Our :ref:`cancellation semantics <cancellable-primitives>` say that |
| 533 |
:exc:`~trio.Cancelled` should only be raised if the operation didn't |
| 534 |
happen. Using :func:`cancel_shielded_checkpoint` on the early-exit |
| 535 |
branch accomplishes this. |
| 536 |
|
| 537 |
* On the path where we do end up blocking, we don't pass through any |
| 538 |
schedule points before that, which avoids some unnecessary work. |
| 539 |
|
| 540 |
* Avoids implicitly chaining the :exc:`BlockingIOError` with any |
| 541 |
errors raised by ``attempt_operation`` or |
| 542 |
``wait_for_operation_to_be_ready``, by keeping the ``while True:`` |
| 543 |
loop outside of the ``except BlockingIOError:`` block. |
| 544 |
|
| 545 |
These functions can also be useful in other situations. For example, |
| 546 |
when :func:`trio.to_thread.run_sync` schedules some work to run in a |
| 547 |
worker thread, it blocks until the work is finished (so it's a |
| 548 |
schedule point), but by default it doesn't allow cancellation. So to |
| 549 |
make sure that the call always acts as a checkpoint, it calls |
| 550 |
:func:`checkpoint_if_cancelled` before starting the thread. |
| 551 |
|
| 552 |
|
| 553 |
Low-level blocking |
| 554 |
------------------ |
| 555 |
|
| 556 |
.. autofunction:: wait_task_rescheduled |
| 557 |
.. autoclass:: Abort |
| 558 |
.. autofunction:: reschedule |
| 559 |
|
| 560 |
Here's an example lock class implemented using |
| 561 |
:func:`wait_task_rescheduled` directly. This implementation has a |
| 562 |
number of flaws, including lack of fairness, O(n) cancellation, |
| 563 |
missing error checking, failure to insert a checkpoint on the |
| 564 |
non-blocking path, etc. If you really want to implement your own lock, |
| 565 |
then you should study the implementation of :class:`trio.Lock` and use |
| 566 |
:class:`ParkingLot`, which handles some of these issues for you. But |
| 567 |
this does serve to illustrate the basic structure of the |
| 568 |
:func:`wait_task_rescheduled` API: |
| 569 |
|
| 570 |
.. code-block:: python |
| 571 |
|
| 572 |
class NotVeryGoodLock: |
| 573 |
def __init__(self): |
| 574 |
self._blocked_tasks = collections.deque() |
| 575 |
self._held = False |
| 576 |
|
| 577 |
async def acquire(self): |
| 578 |
# We might have to try several times to acquire the lock. |
| 579 |
while self._held: |
| 580 |
# Someone else has the lock, so we have to wait. |
| 581 |
task = trio.lowlevel.current_task() |
| 582 |
self._blocked_tasks.append(task) |
| 583 |
def abort_fn(_): |
| 584 |
self._blocked_tasks.remove(task) |
| 585 |
return trio.lowlevel.Abort.SUCCEEDED |
| 586 |
await trio.lowlevel.wait_task_rescheduled(abort_fn) |
| 587 |
# At this point the lock was released -- but someone else |
| 588 |
# might have swooped in and taken it again before we |
| 589 |
# woke up. So we loop around to check the 'while' condition |
| 590 |
# again. |
| 591 |
# if we reach this point, it means that the 'while' condition |
| 592 |
# has just failed, so we know no-one is holding the lock, and |
| 593 |
# we can take it. |
| 594 |
self._held = True |
| 595 |
|
| 596 |
def release(self): |
| 597 |
self._held = False |
| 598 |
if self._blocked_tasks: |
| 599 |
woken_task = self._blocked_tasks.popleft() |
| 600 |
trio.lowlevel.reschedule(woken_task) |
| 601 |
|
| 602 |
|
| 603 |
Task API |
| 604 |
======== |
| 605 |
|
| 606 |
.. autofunction:: current_root_task() |
| 607 |
|
| 608 |
.. autofunction:: current_task() |
| 609 |
|
| 610 |
.. class:: Task() |
| 611 |
|
| 612 |
A :class:`Task` object represents a concurrent "thread" of |
| 613 |
execution. It has no public constructor; Trio internally creates a |
| 614 |
:class:`Task` object for each call to ``nursery.start(...)`` or |
| 615 |
``nursery.start_soon(...)``. |
| 616 |
|
| 617 |
Its public members are mostly useful for introspection and |
| 618 |
debugging: |
| 619 |
|
| 620 |
.. attribute:: name |
| 621 |
|
| 622 |
String containing this :class:`Task`\'s name. Usually the name |
| 623 |
of the function this :class:`Task` is running, but can be |
| 624 |
overridden by passing ``name=`` to ``start`` or ``start_soon``. |
| 625 |
|
| 626 |
.. attribute:: coro |
| 627 |
|
| 628 |
This task's coroutine object. |
| 629 |
|
| 630 |
.. automethod:: iter_await_frames |
| 631 |
|
| 632 |
.. attribute:: context |
| 633 |
|
| 634 |
This task's :class:`contextvars.Context` object. |
| 635 |
|
| 636 |
.. autoattribute:: parent_nursery |
| 637 |
|
| 638 |
.. autoattribute:: eventual_parent_nursery |
| 639 |
|
| 640 |
.. autoattribute:: child_nurseries |
| 641 |
|
| 642 |
.. attribute:: custom_sleep_data |
| 643 |
|
| 644 |
Trio doesn't assign this variable any meaning, except that it |
| 645 |
sets it to ``None`` whenever a task is rescheduled. It can be |
| 646 |
used to share data between the different tasks involved in |
| 647 |
putting a task to sleep and then waking it up again. (See |
| 648 |
:func:`wait_task_rescheduled` for details.) |
| 649 |
|
| 650 |
.. _guest-mode: |
| 651 |
|
| 652 |
Using "guest mode" to run Trio on top of other event loops |
| 653 |
========================================================== |
| 654 |
|
| 655 |
What is "guest mode"? |
| 656 |
--------------------- |
| 657 |
|
| 658 |
An event loop acts as a central coordinator to manage all the IO |
| 659 |
happening in your program. Normally, that means that your application |
| 660 |
has to pick one event loop, and use it for everything. But what if you |
| 661 |
like Trio, but also need to use a framework like `Qt |
| 662 |
<https://en.wikipedia.org/wiki/Qt_(software)>`__ or `PyGame |
| 663 |
<https://www.pygame.org/>`__ that has its own event loop? Then you |
| 664 |
need some way to run both event loops at once. |
| 665 |
|
| 666 |
It is possible to combine event loops, but the standard approaches all |
| 667 |
have significant downsides: |
| 668 |
|
| 669 |
- **Polling:** this is where you use a `busy-loop |
| 670 |
<https://en.wikipedia.org/wiki/Busy_waiting>`__ to manually check |
| 671 |
for IO on both event loops many times per second. This adds latency, |
| 672 |
and wastes CPU time and electricity. |
| 673 |
|
| 674 |
- **Pluggable IO backends:** this is where you reimplement one of the |
| 675 |
event loop APIs on top of the other, so you effectively end up with |
| 676 |
just one event loop. This requires a significant amount of work for |
| 677 |
each pair of event loops you want to integrate, and different |
| 678 |
backends inevitably end up with inconsistent behavior, forcing users |
| 679 |
to program against the least-common-denominator. And if the two |
| 680 |
event loops expose different feature sets, it may not even be |
| 681 |
possible to implement one in terms of the other. |
| 682 |
|
| 683 |
- **Running the two event loops in separate threads:** This works, but |
| 684 |
most event loop APIs aren't thread-safe, so in this approach you |
| 685 |
need to keep careful track of which code runs on which event loop, |
| 686 |
and remember to use explicit inter-thread messaging whenever you |
| 687 |
interact with the other loop – or else risk obscure race conditions |
| 688 |
and data corruption. |
| 689 |
|
| 690 |
That's why Trio offers a fourth option: **guest mode**. Guest mode |
| 691 |
lets you execute `trio.run` on top of some other "host" event loop, |
| 692 |
like Qt. Its advantages are: |
| 693 |
|
| 694 |
- Efficiency: guest mode is event-driven instead of using a busy-loop, |
| 695 |
so it has low latency and doesn't waste electricity. |
| 696 |
|
| 697 |
- No need to think about threads: your Trio code runs in the same |
| 698 |
thread as the host event loop, so you can freely call sync Trio APIs |
| 699 |
from the host, and call sync host APIs from Trio. For example, if |
| 700 |
you're making a GUI app with Qt as the host loop, then making a |
| 701 |
`cancel button <https://doc.qt.io/qt-5/qpushbutton.html>`__ and |
| 702 |
connecting it to a `trio.CancelScope` is as easy as writing: |
| 703 |
|
| 704 |
.. code-block:: python |
| 705 |
|
| 706 |
# Trio code can create Qt objects without any special ceremony... |
| 707 |
my_cancel_button = QPushButton("Cancel") |
| 708 |
# ...and Qt can call back to Trio just as easily |
| 709 |
my_cancel_button.clicked.connect(my_cancel_scope.cancel) |
| 710 |
|
| 711 |
(For async APIs, it's not that simple, but you can use sync APIs to |
| 712 |
build explicit bridges between the two worlds, e.g. by passing async |
| 713 |
functions and their results back and forth through queues.) |
| 714 |
|
| 715 |
- Consistent behavior: guest mode uses the same code as regular Trio: |
| 716 |
the same scheduler, same IO code, same everything. So you get the |
| 717 |
full feature set and everything acts the way you expect. |
| 718 |
|
| 719 |
- Simple integration and broad compatibility: pretty much every event |
| 720 |
loop offers some threadsafe "schedule a callback" operation, and |
| 721 |
that's all you need to use it as a host loop. |
| 722 |
|
| 723 |
|
| 724 |
Really? How is that possible? |
| 725 |
----------------------------- |
| 726 |
|
| 727 |
.. note:: |
| 728 |
|
| 729 |
You can use guest mode without reading this section. It's included |
| 730 |
for those who enjoy understanding how things work. |
| 731 |
|
| 732 |
All event loops have the same basic structure. They loop through two |
| 733 |
operations, over and over: |
| 734 |
|
| 735 |
1. Wait for the operating system to notify them that something |
| 736 |
interesting has happened, like data arriving on a socket or a |
| 737 |
timeout passing. They do this by invoking a platform-specific |
| 738 |
``sleep_until_something_happens()`` system call – ``select``, |
| 739 |
``epoll``, ``kqueue``, ``GetQueuedCompletionEvents``, etc. |
| 740 |
|
| 741 |
2. Run all the user tasks that care about whatever happened, then go |
| 742 |
back to step 1. |
| 743 |
|
| 744 |
The problem here is step 1. Two different event loops on the same |
| 745 |
thread can take turns running user tasks in step 2, but when they're |
| 746 |
idle and nothing is happening, they can't both invoke their own |
| 747 |
``sleep_until_something_happens()`` function at the same time. |
| 748 |
|
| 749 |
The "polling" and "pluggable backend" strategies solve this by hacking |
| 750 |
the loops so both step 1s can run at the same time in the same thread. |
| 751 |
Keeping everything in one thread is great for step 2, but the step 1 |
| 752 |
hacks create problems. |
| 753 |
|
| 754 |
The "separate threads" strategy solves this by moving both steps into |
| 755 |
separate threads. This makes step 1 work, but the downside is that now |
| 756 |
the user tasks in step 2 are running separate threads as well, so |
| 757 |
users are forced to deal with inter-thread coordination. |
| 758 |
|
| 759 |
The idea behind guest mode is to combine the best parts of each |
| 760 |
approach: we move Trio's step 1 into a separate worker thread, while |
| 761 |
keeping Trio's step 2 in the main host thread. This way, when the |
| 762 |
application is idle, both event loops do their |
| 763 |
``sleep_until_something_happens()`` at the same time in their own |
| 764 |
threads. But when the app wakes up and your code is actually running, |
| 765 |
it all happens in a single thread. The threading trickiness is all |
| 766 |
handled transparently inside Trio. |
| 767 |
|
| 768 |
Concretely, we unroll Trio's internal event loop into a chain of |
| 769 |
callbacks, and as each callback finishes, it schedules the next |
| 770 |
callback onto the host loop or a worker thread as appropriate. So the |
| 771 |
only thing the host loop has to provide is a way to schedule a |
| 772 |
callback onto the main thread from a worker thread. |
| 773 |
|
| 774 |
Coordinating between Trio and the host loop does add some overhead. |
| 775 |
The main cost is switching in and out of the background thread, since |
| 776 |
this requires cross-thread messaging. This is cheap (on the order of a |
| 777 |
few microseconds, assuming your host loop is implemented efficiently), |
| 778 |
but it's not free. |
| 779 |
|
| 780 |
But, there's a nice optimization we can make: we only *need* the |
| 781 |
thread when our ``sleep_until_something_happens()`` call actually |
| 782 |
sleeps, that is, when the Trio part of your program is idle and has |
| 783 |
nothing to do. So before we switch into the worker thread, we |
| 784 |
double-check whether we're idle, and if not, then we skip the worker |
| 785 |
thread and jump directly to step 2. This means that your app only pays |
| 786 |
the extra thread-switching penalty at moments when it would otherwise |
| 787 |
be sleeping, so it should have minimal effect on your app's overall |
| 788 |
performance. |
| 789 |
|
| 790 |
The total overhead will depend on your host loop, your platform, your |
| 791 |
application, etc. But we expect that in most cases, apps running in |
| 792 |
guest mode should only be 5-10% slower than the same code using |
| 793 |
`trio.run`. If you find that's not true for your app, then please let |
| 794 |
us know and we'll see if we can fix it! |
| 795 |
|
| 796 |
|
| 797 |
.. _guest-run-implementation: |
| 798 |
|
| 799 |
Implementing guest mode for your favorite event loop |
| 800 |
---------------------------------------------------- |
| 801 |
|
| 802 |
Let's walk through what you need to do to integrate Trio's guest mode |
| 803 |
with your favorite event loop. Treat this section like a checklist. |
| 804 |
|
| 805 |
**Getting started:** The first step is to get something basic working. |
| 806 |
Here's a minimal example of running Trio on top of asyncio, that you |
| 807 |
can use as a model: |
| 808 |
|
| 809 |
.. code-block:: python |
| 810 |
|
| 811 |
import asyncio |
| 812 |
import trio |
| 813 |
|
| 814 |
# A tiny Trio program |
| 815 |
async def trio_main(): |
| 816 |
for _ in range(5): |
| 817 |
print("Hello from Trio!") |
| 818 |
# This is inside Trio, so we have to use Trio APIs |
| 819 |
await trio.sleep(1) |
| 820 |
return "trio done!" |
| 821 |
|
| 822 |
# The code to run it as a guest inside asyncio |
| 823 |
async def asyncio_main(): |
| 824 |
asyncio_loop = asyncio.get_running_loop() |
| 825 |
|
| 826 |
def run_sync_soon_threadsafe(fn): |
| 827 |
asyncio_loop.call_soon_threadsafe(fn) |
| 828 |
|
| 829 |
def done_callback(trio_main_outcome): |
| 830 |
print(f"Trio program ended with: {trio_main_outcome}") |
| 831 |
|
| 832 |
# This is where the magic happens: |
| 833 |
trio.lowlevel.start_guest_run( |
| 834 |
trio_main, |
| 835 |
run_sync_soon_threadsafe=run_sync_soon_threadsafe, |
| 836 |
done_callback=done_callback, |
| 837 |
) |
| 838 |
|
| 839 |
# Let the host loop run for a while to give trio_main time to |
| 840 |
# finish. (WARNING: This is a hack. See below for better |
| 841 |
# approaches.) |
| 842 |
# |
| 843 |
# This function is in asyncio, so we have to use asyncio APIs. |
| 844 |
await asyncio.sleep(10) |
| 845 |
|
| 846 |
asyncio.run(asyncio_main()) |
| 847 |
|
| 848 |
You can see we're using asyncio-specific APIs to start up a loop, and |
| 849 |
then we call `trio.lowlevel.start_guest_run`. This function is very |
| 850 |
similar to `trio.run`, and takes all the same arguments. But it has |
| 851 |
two differences: |
| 852 |
|
| 853 |
First, instead of blocking until ``trio_main`` has finished, it |
| 854 |
schedules ``trio_main`` to start running on top of the host loop, and |
| 855 |
then returns immediately. So ``trio_main`` is running in the |
| 856 |
background – that's why we have to sleep and give it time to finish. |
| 857 |
|
| 858 |
And second, it requires two extra keyword arguments: |
| 859 |
``run_sync_soon_threadsafe``, and ``done_callback``. |
| 860 |
|
| 861 |
For ``run_sync_soon_threadsafe``, we need a function that takes a |
| 862 |
synchronous callback, and schedules it to run on your host loop. And |
| 863 |
this function needs to be "threadsafe" in the sense that you can |
| 864 |
safely call it from any thread. So you need to figure out how to write |
| 865 |
a function that does that using your host loop's API. For asyncio, |
| 866 |
this is easy because `~asyncio.loop.call_soon_threadsafe` does exactly |
| 867 |
what we need; for your loop, it might be more or less complicated. |
| 868 |
|
| 869 |
For ``done_callback``, you pass in a function that Trio will |
| 870 |
automatically invoke when the Trio run finishes, so you know it's done |
| 871 |
and what happened. For this basic starting version, we just print the |
| 872 |
result; in the next section we'll discuss better alternatives. |
| 873 |
|
| 874 |
At this stage you should be able to run a simple Trio program inside |
| 875 |
your host loop. Now we'll turn that prototype into something solid. |
| 876 |
|
| 877 |
|
| 878 |
**Loop lifetimes:** One of the trickiest things in most event loops is |
| 879 |
shutting down correctly. And having two event loops makes this even |
| 880 |
harder! |
| 881 |
|
| 882 |
If you can, we recommend following this pattern: |
| 883 |
|
| 884 |
- Start up your host loop |
| 885 |
- Immediately call `start_guest_run` to start Trio |
| 886 |
- When Trio finishes and your ``done_callback`` is invoked, shut down |
| 887 |
the host loop |
| 888 |
- Make sure that nothing else shuts down your host loop |
| 889 |
|
| 890 |
This way, your two event loops have the same lifetime, and your |
| 891 |
program automatically exits when your Trio function finishes. |
| 892 |
|
| 893 |
Here's how we'd extend our asyncio example to implement this pattern: |
| 894 |
|
| 895 |
.. code-block:: python3 |
| 896 |
:emphasize-lines: 8-11,19-22 |
| 897 |
|
| 898 |
# Improved version, that shuts down properly after Trio finishes |
| 899 |
async def asyncio_main(): |
| 900 |
asyncio_loop = asyncio.get_running_loop() |
| 901 |
|
| 902 |
def run_sync_soon_threadsafe(fn): |
| 903 |
asyncio_loop.call_soon_threadsafe(fn) |
| 904 |
|
| 905 |
# Revised 'done' callback: set a Future |
| 906 |
done_fut = asyncio_loop.create_future() |
| 907 |
def done_callback(trio_main_outcome): |
| 908 |
done_fut.set_result(trio_main_outcome) |
| 909 |
|
| 910 |
trio.lowlevel.start_guest_run( |
| 911 |
trio_main, |
| 912 |
run_sync_soon_threadsafe=run_sync_soon_threadsafe, |
| 913 |
done_callback=done_callback, |
| 914 |
) |
| 915 |
|
| 916 |
# Wait for the guest run to finish |
| 917 |
trio_main_outcome = await done_fut |
| 918 |
# Pass through the return value or exception from the guest run |
| 919 |
return trio_main_outcome.unwrap() |
| 920 |
|
| 921 |
And then you can encapsulate all this machinery in a utility function |
| 922 |
that exposes a `trio.run`-like API, but runs both loops together: |
| 923 |
|
| 924 |
.. code-block:: python |
| 925 |
|
| 926 |
def trio_run_with_asyncio(trio_main, *args, **trio_run_kwargs): |
| 927 |
async def asyncio_main(): |
| 928 |
# same as above |
| 929 |
... |
| 930 |
|
| 931 |
return asyncio.run(asyncio_main()) |
| 932 |
|
| 933 |
Technically, it is possible to use other patterns. But there are some |
| 934 |
important limitations you have to respect: |
| 935 |
|
| 936 |
- **You must let the Trio program run to completion.** Many event |
| 937 |
loops let you stop the event loop at any point, and any pending |
| 938 |
callbacks/tasks/etc. just... don't run. Trio follows a more |
| 939 |
structured system, where you can cancel things, but the code always |
| 940 |
runs to completion, so ``finally`` blocks run, resources are cleaned |
| 941 |
up, etc. If you stop your host loop early, before the |
| 942 |
``done_callback`` is invoked, then that cuts off the Trio run in the |
| 943 |
middle without a chance to clean up. This can leave your code in an |
| 944 |
inconsistent state, and will definitely leave Trio's internals in an |
| 945 |
inconsistent state, which will cause errors if you try to use Trio |
| 946 |
again in that thread. |
| 947 |
|
| 948 |
Some programs need to be able to quit at any time, for example in |
| 949 |
response to a GUI window being closed or a user selecting a "Quit" |
| 950 |
from a menu. In these cases, we recommend wrapping your whole |
| 951 |
program in a `trio.CancelScope`, and cancelling it when you want to |
| 952 |
quit. |
| 953 |
|
| 954 |
- Each host loop can only have one `start_guest_run` at a time. If you |
| 955 |
try to start a second one, you'll get an error. If you need to run |
| 956 |
multiple Trio functions at the same time, then start up a single |
| 957 |
Trio run, open a nursery, and then start your functions as child |
| 958 |
tasks in that nursery. |
| 959 |
|
| 960 |
- Unless you or your host loop register a handler for `signal.SIGINT` |
| 961 |
before starting Trio (this is not common), then Trio will take over |
| 962 |
delivery of `KeyboardInterrupt`\s. And since Trio can't tell which |
| 963 |
host code is safe to interrupt, it will only deliver |
| 964 |
`KeyboardInterrupt` into the Trio part of your code. This is fine if |
| 965 |
your program is set up to exit when the Trio part exits, because the |
| 966 |
`KeyboardInterrupt` will propagate out of Trio and then trigger the |
| 967 |
shutdown of your host loop, which is just what you want. |
| 968 |
|
| 969 |
Given these constraints, we think the simplest approach is to always |
| 970 |
start and stop the two loops together. |
| 971 |
|
| 972 |
**Signal management:** `"Signals" |
| 973 |
<https://en.wikipedia.org/wiki/Signal_(IPC)>`__ are a low-level |
| 974 |
inter-process communication primitive. When you hit control-C to kill |
| 975 |
a program, that uses a signal. Signal handling in Python has `a lot of |
| 976 |
moving parts |
| 977 |
<https://vorpus.org/blog/control-c-handling-in-python-and-trio/>`__. |
| 978 |
One of those parts is `signal.set_wakeup_fd`, which event loops use to |
| 979 |
make sure that they wake up when a signal arrives so they can respond |
| 980 |
to it. (If you've ever had an event loop ignore you when you hit |
| 981 |
control-C, it was probably because they weren't using |
| 982 |
`signal.set_wakeup_fd` correctly.) |
| 983 |
|
| 984 |
But, only one event loop can use `signal.set_wakeup_fd` at a time. And |
| 985 |
in guest mode that can cause problems: Trio and the host loop might |
| 986 |
start fighting over who's using `signal.set_wakeup_fd`. |
| 987 |
|
| 988 |
Some event loops, like asyncio, won't work correctly unless they win |
| 989 |
this fight. Fortunately, Trio is a little less picky: as long as |
| 990 |
*someone* makes sure that the program wakes up when a signal arrives, |
| 991 |
it should work correctly. So if your host loop wants |
| 992 |
`signal.set_wakeup_fd`, then you should disable Trio's |
| 993 |
`signal.set_wakeup_fd` support, and then both loops will work |
| 994 |
correctly. |
| 995 |
|
| 996 |
On the other hand, if your host loop doesn't use |
| 997 |
`signal.set_wakeup_fd`, then the only way to make everything work |
| 998 |
correctly is to *enable* Trio's `signal.set_wakeup_fd` support. |
| 999 |
|
| 1000 |
By default, Trio assumes that your host loop doesn't use |
| 1001 |
`signal.set_wakeup_fd`. It does try to detect when this creates a |
| 1002 |
conflict with the host loop, and print a warning – but unfortunately, |
| 1003 |
by the time it detects it, the damage has already been done. So if |
| 1004 |
you're getting this warning, then you should disable Trio's |
| 1005 |
`signal.set_wakeup_fd` support by passing |
| 1006 |
``host_uses_signal_set_wakeup_fd=True`` to `start_guest_run`. |
| 1007 |
|
| 1008 |
If you aren't seeing any warnings with your initial prototype, you're |
| 1009 |
*probably* fine. But the only way to be certain is to check your host |
| 1010 |
loop's source. For example, asyncio may or may not use |
| 1011 |
`signal.set_wakeup_fd` depending on the Python version and operating |
| 1012 |
system. |
| 1013 |
|
| 1014 |
|
| 1015 |
**A small optimization:** Finally, consider a small optimization. Some |
| 1016 |
event loops offer two versions of their "call this function soon" API: |
| 1017 |
one that can be used from any thread, and one that can only be used |
| 1018 |
from the event loop thread, with the latter being cheaper. For |
| 1019 |
example, asyncio has both `~asyncio.loop.call_soon_threadsafe` and |
| 1020 |
`~asyncio.loop.call_soon`. |
| 1021 |
|
| 1022 |
If you have a loop like this, then you can also pass a |
| 1023 |
``run_sync_soon_not_threadsafe=...`` kwarg to `start_guest_run`, and |
| 1024 |
Trio will automatically use it when appropriate. |
| 1025 |
|
| 1026 |
If your loop doesn't have a split like this, then don't worry about |
| 1027 |
it; ``run_sync_soon_not_threadsafe=`` is optional. (If it's not |
| 1028 |
passed, then Trio will just use your threadsafe version in all cases.) |
| 1029 |
|
| 1030 |
**That's it!** If you've followed all these steps, you should now have |
| 1031 |
a cleanly-integrated hybrid event loop. Go make some cool |
| 1032 |
GUIs/games/whatever! |
| 1033 |
|
| 1034 |
|
| 1035 |
Limitations |
| 1036 |
----------- |
| 1037 |
|
| 1038 |
In general, almost all Trio features should work in guest mode. The |
| 1039 |
exception is features which rely on Trio having a complete picture of |
| 1040 |
everything that your program is doing, since obviously, it can't |
| 1041 |
control the host loop or see what it's doing. |
| 1042 |
|
| 1043 |
Custom clocks can be used in guest mode, but they only affect Trio |
| 1044 |
timeouts, not host loop timeouts. And the :ref:`autojump clock |
| 1045 |
<testing-time>` and related `trio.testing.wait_all_tasks_blocked` can |
| 1046 |
technically be used in guest mode, but they'll only take Trio tasks |
| 1047 |
into account when decided whether to jump the clock or whether all |
| 1048 |
tasks are blocked. |
| 1049 |
|
| 1050 |
|
| 1051 |
Reference |
| 1052 |
--------- |
| 1053 |
|
| 1054 |
.. autofunction:: start_guest_run |
| 1055 |
|
| 1056 |
|
| 1057 |
.. _live-coroutine-handoff: |
| 1058 |
|
| 1059 |
Handing off live coroutine objects between coroutine runners |
| 1060 |
============================================================ |
| 1061 |
|
| 1062 |
Internally, Python's async/await syntax is built around the idea of |
| 1063 |
"coroutine objects" and "coroutine runners". A coroutine object |
| 1064 |
represents the state of an async callstack. But by itself, this is |
| 1065 |
just a static object that sits there. If you want it to do anything, |
| 1066 |
you need a coroutine runner to push it forward. Every Trio task has an |
| 1067 |
associated coroutine object (see :data:`Task.coro`), and the Trio |
| 1068 |
scheduler acts as their coroutine runner. |
| 1069 |
|
| 1070 |
But of course, Trio isn't the only coroutine runner in Python – |
| 1071 |
:mod:`asyncio` has one, other event loops have them, you can even |
| 1072 |
define your own. |
| 1073 |
|
| 1074 |
And in some very, very unusual circumstances, it even makes sense to |
| 1075 |
transfer a single coroutine object back and forth between different |
| 1076 |
coroutine runners. That's what this section is about. This is an |
| 1077 |
*extremely* exotic use case, and assumes a lot of expertise in how |
| 1078 |
Python async/await works internally. For motivating examples, see |
| 1079 |
`trio-asyncio issue #42 |
| 1080 |
<https://github.com/python-trio/trio-asyncio/issues/42>`__, and `trio |
| 1081 |
issue #649 <https://github.com/python-trio/trio/issues/649>`__. For |
| 1082 |
more details on how coroutines work, we recommend André Caron's `A |
| 1083 |
tale of event loops |
| 1084 |
<https://github.com/AndreLouisCaron/a-tale-of-event-loops>`__, or |
| 1085 |
going straight to :pep:`492` for the full details. |
| 1086 |
|
| 1087 |
.. autofunction:: permanently_detach_coroutine_object |
| 1088 |
|
| 1089 |
.. autofunction:: temporarily_detach_coroutine_object |
| 1090 |
|
| 1091 |
.. autofunction:: reattach_detached_coroutine_object |