Debian Codegraph @

docs/source/reference-core.rst

raw
1 Trio's core functionality
2 =========================
3
4 .. module:: trio
5
6
7 Entering Trio
8 -------------
9
10 If you want to use Trio, then the first thing you have to do is call
11 :func:`trio.run`:
12
13 .. autofunction:: run
14
15
16 General principles
17 ------------------
18
19 .. _checkpoints:
20
21 Checkpoints
22 ~~~~~~~~~~~
23
24 When writing code using Trio, it's very important to understand the
25 concept of a *checkpoint*. Many of Trio's functions act as checkpoints.
26
27 A checkpoint is two things:
28
29 1. It's a point where Trio checks for cancellation. For example, if
30 the code that called your function set a timeout, and that timeout
31 has expired, then the next time your function executes a checkpoint
32 Trio will raise a :exc:`Cancelled` exception. See
33 :ref:`cancellation` below for more details.
34
35 2. It's a point where the Trio scheduler checks its scheduling policy
36 to see if it's a good time to switch to another task, and
37 potentially does so. (Currently, this check is very simple: the
38 scheduler always switches at every checkpoint. But `this might
39 change in the future
40 <https://github.com/python-trio/trio/issues/32>`__.)
41
42 When writing Trio code, you need to keep track of where your
43 checkpoints are. Why? First, because checkpoints require extra
44 scrutiny: whenever you execute a checkpoint, you need to be prepared
45 to handle a :exc:`Cancelled` error, or for another task to run and
46 `rearrange some state out from under you
47 <https://glyph.twistedmatrix.com/2014/02/unyielding.html>`__. And
48 second, because you also need to make sure that you have *enough*
49 checkpoints: if your code doesn't pass through a checkpoint on a
50 regular basis, then it will be slow to notice and respond to
51 cancellation and – much worse – since Trio is a cooperative
52 multi-tasking system where the *only* place the scheduler can switch
53 tasks is at checkpoints, it'll also prevent the scheduler from fairly
54 allocating time between different tasks and adversely effect the
55 response latency of all the other code running in the same
56 process. (Informally we say that a task that does this is "hogging the
57 run loop".)
58
59 So when you're doing code review on a project that uses Trio, one of
60 the things you'll want to think about is whether there are enough
61 checkpoints, and whether each one is handled correctly. Of course this
62 means you need a way to recognize checkpoints. How do you do that?
63 The underlying principle is that any operation that blocks has to be a
64 checkpoint. This makes sense: if an operation blocks, then it might
65 block for a long time, and you'll want to be able to cancel it if a
66 timeout expires; and in any case, while this task is blocked we want
67 another task to be scheduled to run so our code can make full use of
68 the CPU.
69
70 But if we want to write correct code in practice, then this principle
71 is a little too sloppy and imprecise to be useful. How do we know
72 which functions might block? What if a function blocks sometimes, but
73 not others, depending on the arguments passed / network speed / phase
74 of the moon? How do we figure out where the checkpoints are when
75 we're stressed and sleep deprived but still want to get this code
76 review right, and would prefer to reserve our mental energy for
77 thinking about the actual logic instead of worrying about checkpoints?
78
79 .. _checkpoint-rule:
80
81 Don't worry – Trio's got your back. Since checkpoints are important
82 and ubiquitous, we make it as simple as possible to keep track of
83 them. Here are the rules:
84
85 * Regular (synchronous) functions never contain any checkpoints.
86
87 * If you call an async function provided by Trio (``await
88 <something in trio>``), and it doesn't raise an exception,
89 then it *always* acts as a checkpoint. (If it does raise an
90 exception, it might act as a checkpoint or might not.)
91
92 * This includes async iterators: If you write ``async for ... in <a
93 trio object>``, then there will be at least one checkpoint in
94 each iteration of the loop, and it will still checkpoint if the
95 iterable is empty.
96
97 * Partial exception for async context managers:
98 Both the entry and exit of an ``async with`` block are
99 defined as async functions; but for a
100 particular type of async context manager, it's often the
101 case that only one of them is able to block, which means
102 only that one will act as a checkpoint. This is documented
103 on a case-by-case basis.
104
105 * :func:`trio.open_nursery` is a further exception to this rule.
106
107 * Third-party async functions / iterators / context managers can act
108 as checkpoints; if you see ``await <something>`` or one of its
109 friends, then that *might* be a checkpoint. So to be safe, you
110 should prepare for scheduling or cancellation happening there.
111
112 The reason we distinguish between Trio functions and other functions
113 is that we can't make any guarantees about third party
114 code. Checkpoint-ness is a transitive property: if function A acts as
115 a checkpoint, and you write a function that calls function A, then
116 your function also acts as a checkpoint. If you don't, then it
117 isn't. So there's nothing stopping someone from writing a function
118 like:
119
120 .. code-block:: python
121
122 # technically legal, but bad style:
123 async def why_is_this_async():
124 return 7
125
126 that never calls any of Trio's async functions. This is an async
127 function, but it's not a checkpoint. But why make a function async if
128 it never calls any async functions? It's possible, but it's a bad
129 idea. If you have a function that's not calling any async functions,
130 then you should make it synchronous. The people who use your function
131 will thank you, because it makes it obvious that your function is not
132 a checkpoint, and their code reviews will go faster.
133
134 (Remember how in the tutorial we emphasized the importance of the
135 :ref:`"async sandwich" <async-sandwich>`, and the way it means that
136 ``await`` ends up being a marker that shows when you're calling a
137 function that calls a function that ... eventually calls one of Trio's
138 built-in async functions? The transitivity of async-ness is a
139 technical requirement that Python imposes, but since it exactly
140 matches the transitivity of checkpoint-ness, we're able to exploit it
141 to help you keep track of checkpoints. Pretty sneaky, eh?)
142
143 A slightly trickier case is a function like:
144
145 .. code-block:: python
146
147 async def sleep_or_not(should_sleep):
148 if should_sleep:
149 await trio.sleep(1)
150 else:
151 pass
152
153 Here the function acts as a checkpoint if you call it with
154 ``should_sleep`` set to a true value, but not otherwise. This is why
155 we emphasize that Trio's own async functions are *unconditional* checkpoints:
156 they *always* check for cancellation and check for scheduling,
157 regardless of what arguments they're passed. If you find an async
158 function in Trio that doesn't follow this rule, then it's a bug and
159 you should `let us know
160 <https://github.com/python-trio/trio/issues>`__.
161
162 Inside Trio, we're very picky about this, because Trio is the
163 foundation of the whole system so we think it's worth the extra effort
164 to make things extra predictable. It's up to you how picky you want to
165 be in your code. To give you a more realistic example of what this
166 kind of issue looks like in real life, consider this function:
167
168 .. code-block:: python
169
170 async def recv_exactly(sock, nbytes):
171 data = bytearray()
172 while nbytes > 0:
173 # recv() reads up to 'nbytes' bytes each time
174 chunk = await sock.recv(nbytes)
175 if not chunk:
176 raise RuntimeError("socket unexpected closed")
177 nbytes -= len(chunk)
178 data += chunk
179 return data
180
181 If called with an ``nbytes`` that's greater than zero, then it will
182 call ``sock.recv`` at least once, and ``recv`` is an async Trio
183 function, and thus an unconditional checkpoint. So in this case,
184 ``recv_exactly`` acts as a checkpoint. But if we do ``await
185 recv_exactly(sock, 0)``, then it will immediately return an empty
186 buffer without executing a checkpoint. If this were a function in
187 Trio itself, then this wouldn't be acceptable, but you may decide you
188 don't want to worry about this kind of minor edge case in your own
189 code.
190
191 If you do want to be careful, or if you have some CPU-bound code that
192 doesn't have enough checkpoints in it, then it's useful to know that
193 ``await trio.sleep(0)`` is an idiomatic way to execute a checkpoint
194 without doing anything else, and that
195 :func:`trio.testing.assert_checkpoints` can be used to test that an
196 arbitrary block of code contains a checkpoint.
197
198
199 Thread safety
200 ~~~~~~~~~~~~~
201
202 The vast majority of Trio's API is *not* thread safe: it can only be
203 used from inside a call to :func:`trio.run`. This manual doesn't
204 bother documenting this on individual calls; unless specifically noted
205 otherwise, you should assume that it isn't safe to call any Trio
206 functions from anywhere except the Trio thread. (But :ref:`see below
207 <threads>` if you really do need to work with threads.)
208
209
210 .. _time-and-clocks:
211
212 Time and clocks
213 ---------------
214
215 Every call to :func:`run` has an associated clock.
216
217 By default, Trio uses an unspecified monotonic clock, but this can be
218 changed by passing a custom clock object to :func:`run` (e.g. for
219 testing).
220
221 You should not assume that Trio's internal clock matches any other
222 clock you have access to, including the clocks of simultaneous calls
223 to :func:`trio.run` happening in other processes or threads!
224
225 The default clock is currently implemented as :func:`time.perf_counter`
226 plus a large random offset. The idea here is to catch code that
227 accidentally uses :func:`time.perf_counter` early, which should help keep
228 our options open for `changing the clock implementation later
229 <https://github.com/python-trio/trio/issues/33>`__, and (more importantly)
230 make sure you can be confident that custom clocks like
231 :class:`trio.testing.MockClock` will work with third-party libraries
232 you don't control.
233
234 .. autofunction:: current_time
235
236 .. autofunction:: sleep
237 .. autofunction:: sleep_until
238 .. autofunction:: sleep_forever
239
240 If you're a mad scientist or otherwise feel the need to take direct
241 control over the PASSAGE OF TIME ITSELF, then you can implement a
242 custom :class:`~trio.abc.Clock` class:
243
244 .. autoclass:: trio.abc.Clock
245 :members:
246
247
248 .. _cancellation:
249
250 Cancellation and timeouts
251 -------------------------
252
253 Trio has a rich, composable system for cancelling work, either
254 explicitly or when a timeout expires.
255
256
257 A simple timeout example
258 ~~~~~~~~~~~~~~~~~~~~~~~~
259
260 In the simplest case, you can apply a timeout to a block of code:
261
262 .. code-block:: python
263
264 with trio.move_on_after(30):
265 result = await do_http_get("https://...")
266 print("result is", result)
267 print("with block finished")
268
269 We refer to :func:`move_on_after` as creating a "cancel scope", which
270 contains all the code that runs inside the ``with`` block. If the HTTP
271 request takes more than 30 seconds to run, then it will be cancelled:
272 we'll abort the request and we *won't* see ``result is ...`` printed
273 on the console; instead we'll go straight to printing the ``with block
274 finished`` message.
275
276 .. note::
277
278 Note that this is a single 30 second timeout for the entire body of
279 the ``with`` statement. This is different from what you might have
280 seen with other Python libraries, where timeouts often refer to
281 something `more complicated
282 <https://requests.kennethreitz.org/en/master/user/quickstart/#timeouts>`__. We
283 think this way is easier to reason about.
284
285 How does this work? There's no magic here: Trio is built using
286 ordinary Python functionality, so we can't just abandon the code
287 inside the ``with`` block. Instead, we take advantage of Python's
288 standard way of aborting a large and complex piece of code: we raise
289 an exception.
290
291 Here's the idea: whenever you call a cancellable function like ``await
292 trio.sleep(...)`` or ``await sock.recv(...)`` – see :ref:`checkpoints`
293 – then the first thing that function does is to check if there's a
294 surrounding cancel scope whose timeout has expired, or otherwise been
295 cancelled. If so, then instead of performing the requested operation,
296 the function fails immediately with a :exc:`Cancelled` exception. In
297 this example, this probably happens somewhere deep inside the bowels
298 of ``do_http_get``. The exception then propagates out like any normal
299 exception (you could even catch it if you wanted, but that's generally
300 a bad idea), until it reaches the ``with move_on_after(...):``. And at
301 this point, the :exc:`Cancelled` exception has done its job – it's
302 successfully unwound the whole cancelled scope – so
303 :func:`move_on_after` catches it, and execution continues as normal
304 after the ``with`` block. And this all works correctly even if you
305 have nested cancel scopes, because every :exc:`Cancelled` object
306 carries an invisible marker that makes sure that the cancel scope that
307 triggered it is the only one that will catch it.
308
309
310 Handling cancellation
311 ~~~~~~~~~~~~~~~~~~~~~
312
313 Pretty much any code you write using Trio needs to have some strategy
314 to handle :exc:`Cancelled` exceptions – even if you didn't set a
315 timeout, then your caller might (and probably will).
316
317 You can catch :exc:`Cancelled`, but you shouldn't! Or more precisely,
318 if you do catch it, then you should do some cleanup and then re-raise
319 it or otherwise let it continue propagating (unless you encounter an
320 error, in which case it's OK to let that propagate instead). To help
321 remind you of this fact, :exc:`Cancelled` inherits from
322 :exc:`BaseException`, like :exc:`KeyboardInterrupt` and
323 :exc:`SystemExit` do, so that it won't be caught by catch-all ``except
324 Exception:`` blocks.
325
326 It's also important in any long-running code to make sure that you
327 regularly check for cancellation, because otherwise timeouts won't
328 work! This happens implicitly every time you call a cancellable
329 operation; see :ref:`below <cancellable-primitives>` for details. If
330 you have a task that has to do a lot of work without any I/O, then you
331 can use ``await sleep(0)`` to insert an explicit cancel+schedule
332 point.
333
334 Here's a rule of thumb for designing good Trio-style ("trionic"?)
335 APIs: if you're writing a reusable function, then you shouldn't take a
336 ``timeout=`` parameter, and instead let your caller worry about
337 it. This has several advantages. First, it leaves the caller's options
338 open for deciding how they prefer to handle timeouts – for example,
339 they might find it easier to work with absolute deadlines instead of
340 relative timeouts. If they're the ones calling into the cancellation
341 machinery, then they get to pick, and you don't have to worry about
342 it. Second, and more importantly, this makes it easier for others to
343 reuse your code. If you write a ``http_get`` function, and then I come
344 along later and write a ``log_in_to_twitter`` function that needs to
345 internally make several ``http_get`` calls, I don't want to have to
346 figure out how to configure the individual timeouts on each of those
347 calls – and with Trio's timeout system, it's totally unnecessary.
348
349 Of course, this rule doesn't apply to APIs that need to impose
350 internal timeouts. For example, if you write a ``start_http_server``
351 function, then you probably should give your caller some way to
352 configure timeouts on individual requests.
353
354
355 Cancellation semantics
356 ~~~~~~~~~~~~~~~~~~~~~~
357
358 You can freely nest cancellation blocks, and each :exc:`Cancelled`
359 exception "knows" which block it belongs to. So long as you don't stop
360 it, the exception will keep propagating until it reaches the block
361 that raised it, at which point it will stop automatically.
362
363 Here's an example:
364
365 .. code-block:: python
366
367 print("starting...")
368 with trio.move_on_after(5):
369 with trio.move_on_after(10):
370 await trio.sleep(20)
371 print("sleep finished without error")
372 print("move_on_after(10) finished without error")
373 print("move_on_after(5) finished without error")
374
375 In this code, the outer scope will expire after 5 seconds, causing the
376 :func:`sleep` call to return early with a :exc:`Cancelled`
377 exception. Then this exception will propagate through the ``with
378 move_on_after(10)`` line until it's caught by the ``with
379 move_on_after(5)`` context manager. So this code will print:
380
381 .. code-block:: none
382
383 starting...
384 move_on_after(5) finished without error
385
386 The end result is that Trio has successfully cancelled exactly the
387 work that was happening within the scope that was cancelled.
388
389 Looking at this, you might wonder how you can tell whether the inner
390 block timed out – perhaps you want to do something different, like try
391 a fallback procedure or report a failure to our caller. To make this
392 easier, :func:`move_on_after`\´s ``__enter__`` function returns an
393 object representing this cancel scope, which we can use to check
394 whether this scope caught a :exc:`Cancelled` exception:
395
396 .. code-block:: python
397
398 with trio.move_on_after(5) as cancel_scope:
399 await trio.sleep(10)
400 print(cancel_scope.cancelled_caught) # prints "True"
401
402 The ``cancel_scope`` object also allows you to check or adjust this
403 scope's deadline, explicitly trigger a cancellation without waiting
404 for the deadline, check if the scope has already been cancelled, and
405 so forth – see :class:`CancelScope` below for the full details.
406
407 .. _blocking-cleanup-example:
408
409 Cancellations in Trio are "level triggered", meaning that once a block
410 has been cancelled, *all* cancellable operations in that block will
411 keep raising :exc:`Cancelled`. This helps avoid some pitfalls around
412 resource clean-up. For example, imagine that we have a function that
413 connects to a remote server and sends some messages, and then cleans
414 up on the way out:
415
416 .. code-block:: python
417
418 with trio.move_on_after(TIMEOUT):
419 conn = make_connection()
420 try:
421 await conn.send_hello_msg()
422 finally:
423 await conn.send_goodbye_msg()
424
425 Now suppose that the remote server stops responding, so our call to
426 ``await conn.send_hello_msg()`` hangs forever. Fortunately, we were
427 clever enough to put a timeout around this code, so eventually the
428 timeout will expire and ``send_hello_msg`` will raise
429 :exc:`Cancelled`. But then, in the ``finally`` block, we make another
430 blocking operation, which will also hang forever! At this point, if we
431 were using :mod:`asyncio` or another library with "edge-triggered"
432 cancellation, we'd be in trouble: since our timeout already fired, it
433 wouldn't fire again, and at this point our application would lock up
434 forever. But in Trio, this *doesn't* happen: the ``await
435 conn.send_goodbye_msg()`` call is still inside the cancelled block, so
436 it will also raise :exc:`Cancelled`.
437
438 Of course, if you really want to make another blocking call in your
439 cleanup handler, Trio will let you; it's trying to prevent you from
440 accidentally shooting yourself in the foot. Intentional foot-shooting
441 is no problem (or at least – it's not Trio's problem). To do this,
442 create a new scope, and set its :attr:`~CancelScope.shield`
443 attribute to :data:`True`:
444
445 .. code-block:: python
446
447 with trio.move_on_after(TIMEOUT):
448 conn = make_connection()
449 try:
450 await conn.send_hello_msg()
451 finally:
452 with trio.move_on_after(CLEANUP_TIMEOUT, shield=True) as cleanup_scope:
453 await conn.send_goodbye_msg()
454
455 So long as you're inside a scope with ``shield = True`` set, then
456 you'll be protected from outside cancellations. Note though that this
457 *only* applies to *outside* cancellations: if ``CLEANUP_TIMEOUT``
458 expires then ``await conn.send_goodbye_msg()`` will still be
459 cancelled, and if ``await conn.send_goodbye_msg()`` call uses any
460 timeouts internally, then those will continue to work normally as
461 well. This is a pretty advanced feature that most people probably
462 won't use, but it's there for the rare cases where you need it.
463
464
465 .. _cancellable-primitives:
466
467 Cancellation and primitive operations
468 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
469
470 We've talked a lot about what happens when an operation is cancelled,
471 and how you need to be prepared for this whenever calling a
472 cancellable operation... but we haven't gone into the details about
473 which operations are cancellable, and how exactly they behave when
474 they're cancelled.
475
476 Here's the rule: if it's in the ``trio`` namespace, and you use ``await``
477 to call it, then it's cancellable (see :ref:`checkpoints`
478 above). Cancellable means:
479
480 * If you try to call it when inside a cancelled scope, then it will
481 raise :exc:`Cancelled`.
482
483 * If it blocks, and while it's blocked then one of the scopes around
484 it becomes cancelled, it will return early and raise
485 :exc:`Cancelled`.
486
487 * Raising :exc:`Cancelled` means that the operation *did not
488 happen*. If a Trio socket's ``send`` method raises :exc:`Cancelled`,
489 then no data was sent. If a Trio socket's ``recv`` method raises
490 :exc:`Cancelled` then no data was lost – it's still sitting in the
491 socket receive buffer waiting for you to call ``recv`` again. And so
492 forth.
493
494 There are a few idiosyncratic cases where external constraints make it
495 impossible to fully implement these semantics. These are always
496 documented. There is also one systematic exception:
497
498 * Async cleanup operations – like ``__aexit__`` methods or async close
499 methods – are cancellable just like anything else *except* that if
500 they are cancelled, they still perform a minimum level of cleanup
501 before raising :exc:`Cancelled`.
502
503 For example, closing a TLS-wrapped socket normally involves sending a
504 notification to the remote peer, so that they can be cryptographically
505 assured that you really meant to close the socket, and your connection
506 wasn't just broken by a man-in-the-middle attacker. But handling this
507 robustly is a bit tricky. Remember our :ref:`example
508 <blocking-cleanup-example>` above where the blocking
509 ``send_goodbye_msg`` caused problems? That's exactly how closing a TLS
510 socket works: if the remote peer has disappeared, then our code may
511 never be able to actually send our shutdown notification, and it would
512 be nice if it didn't block forever trying. Therefore, the method for
513 closing a TLS-wrapped socket will *try* to send that notification –
514 and if it gets cancelled, then it will give up on sending the message,
515 but *will* still close the underlying socket before raising
516 :exc:`Cancelled`, so at least you don't leak that resource.
517
518
519 Cancellation API details
520 ~~~~~~~~~~~~~~~~~~~~~~~~
521
522 :func:`move_on_after` and all the other cancellation facilities provided
523 by Trio are ultimately implemented in terms of :class:`CancelScope`
524 objects.
525
526 .. autoclass:: trio.CancelScope
527
528 .. autoattribute:: deadline
529
530 .. autoattribute:: relative_deadline
531
532 .. autoattribute:: shield
533
534 .. automethod:: is_relative()
535
536 .. automethod:: cancel()
537
538 .. attribute:: cancelled_caught
539
540 Readonly :class:`bool`. Records whether this scope caught a
541 :exc:`~trio.Cancelled` exception. This requires two things: (1)
542 the ``with`` block exited with a :exc:`~trio.Cancelled`
543 exception, and (2) this scope is the one that was responsible
544 for triggering this :exc:`~trio.Cancelled` exception.
545
546 .. autoattribute:: cancel_called
547
548 Often there is no need to create :class:`CancelScope` object. Trio
549 already includes :attr:`~trio.Nursery.cancel_scope` attribute in a
550 task-related :class:`Nursery` object. We will cover nurseries later in
551 the manual.
552
553 Trio also provides several convenience functions for the common
554 situation of just wanting to impose a timeout on some code:
555
556 .. autofunction:: move_on_after
557 :with: cancel_scope
558
559 .. autofunction:: move_on_at
560 :with: cancel_scope
561
562 .. autofunction:: fail_after
563 :with: cancel_scope
564
565 .. autofunction:: fail_at
566 :with: cancel_scope
567
568 Cheat sheet
569 +++++++++++
570
571 * If you want to impose a timeout on a function, but you don't care
572 whether it timed out or not:
573
574 .. code-block:: python
575
576 with trio.move_on_after(TIMEOUT):
577 await do_whatever()
578 # carry on!
579
580 * If you want to impose a timeout on a function, and then do some
581 recovery if it timed out:
582
583 .. code-block:: python
584
585 with trio.move_on_after(TIMEOUT) as cancel_scope:
586 await do_whatever()
587 if cancel_scope.cancelled_caught:
588 # The operation timed out, try something else
589 try_to_recover()
590
591 * If you want to impose a timeout on a function, and then if it times
592 out then just give up and raise an error for your caller to deal
593 with:
594
595 .. code-block:: python
596
597 with trio.fail_after(TIMEOUT):
598 await do_whatever()
599
600 It's also possible to check what the current effective deadline is,
601 which is sometimes useful:
602
603 .. autofunction:: current_effective_deadline
604
605 .. _tasks:
606
607 Tasks let you do multiple things at once
608 ----------------------------------------
609
610 One of Trio's core design principles is: *no implicit
611 concurrency*. Every function executes in a straightforward,
612 top-to-bottom manner, finishing each operation before moving on to the
613 next – *like Guido intended*.
614
615 But, of course, the entire point of an async library is to let you do
616 multiple things at once. The one and only way to do that in Trio is
617 through the task spawning interface. So if you want your program to
618 walk *and* chew gum, this is the section for you.
619
620
621 Nurseries and spawning
622 ~~~~~~~~~~~~~~~~~~~~~~
623
624 Most libraries for concurrent programming let you start new child
625 tasks (or threads, or whatever) willy-nilly, whenever and where-ever
626 you feel like it. Trio is a bit different: you can't start a child
627 task unless you're prepared to be a responsible parent. The way you
628 demonstrate your responsibility is by creating a nursery:
629
630 .. code-block:: python
631
632 async with trio.open_nursery() as nursery:
633 ...
634
635 And once you have a reference to a nursery object, you can start
636 children in that nursery:
637
638 .. code-block:: python
639
640 async def child():
641 ...
642
643 async def parent():
644 async with trio.open_nursery() as nursery:
645 # Make two concurrent calls to child()
646 nursery.start_soon(child)
647 nursery.start_soon(child)
648
649 This means that tasks form a tree: when you call :func:`run`, then
650 this creates an initial task, and all your other tasks will be
651 children, grandchildren, etc. of the initial task.
652
653 Essentially, the body of the ``async with`` block acts like an initial
654 task that's running inside the nursery, and then each call to
655 ``nursery.start_soon`` adds another task that runs in parallel. Two
656 crucial things to keep in mind:
657
658 * If any task inside the nursery finishes with an unhandled exception,
659 then the nursery immediately cancels all the tasks inside the
660 nursery.
661
662 * Since all of the tasks are running concurrently inside the ``async
663 with`` block, the block does not exit until *all* tasks have
664 completed. If you've used other concurrency frameworks, then you can
665 think of it as, the de-indentation at the end of the ``async with``
666 automatically "joins" (waits for) all of the tasks in the nursery.
667
668 * Once all the tasks have finished, then:
669
670 * The nursery is marked as "closed", meaning that no new tasks can
671 be started inside it.
672
673 * Any unhandled exceptions are re-raised inside the parent task, grouped into a
674 single :exc:`BaseExceptionGroup` or :exc:`ExceptionGroup` exception.
675
676 Since all tasks are descendents of the initial task, one consequence
677 of this is that :func:`run` can't finish until all tasks have
678 finished.
679
680 .. note::
681
682 A return statement will not cancel the nursery if it still has tasks running:
683
684 .. code-block:: python
685
686 async def main():
687 async with trio.open_nursery() as nursery:
688 nursery.start_soon(trio.sleep, 5)
689 return
690
691 trio.run(main)
692
693 This code will wait 5 seconds (for the child task to finish), and then return.
694
695 Child tasks and cancellation
696 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
697
698 In Trio, child tasks inherit the parent nursery's cancel scopes. So in
699 this example, both the child tasks will be cancelled when the timeout
700 expires:
701
702 .. code-block:: python
703
704 with trio.move_on_after(TIMEOUT):
705 async with trio.open_nursery() as nursery:
706 nursery.start_soon(child1)
707 nursery.start_soon(child2)
708
709 Note that what matters here is the scopes that were active when
710 :func:`open_nursery` was called, *not* the scopes active when
711 ``start_soon`` is called. So for example, the timeout block below does
712 nothing at all:
713
714 .. code-block:: python
715
716 async with trio.open_nursery() as nursery:
717 with trio.move_on_after(TIMEOUT): # don't do this!
718 nursery.start_soon(child)
719
720 Why is this so? Well, ``start_soon()`` returns as soon as it has scheduled the new task to start running. The flow of execution in the parent then continues on to exit the ``with trio.move_on_after(TIMEOUT):`` block, at which point Trio forgets about the timeout entirely. In order for the timeout to apply to the child task, Trio must be able to tell that its associated cancel scope will stay open for at least as long as the child task is executing. And Trio can only know that for sure if the cancel scope block is outside the nursery block.
721
722 You might wonder why Trio can't just remember "this task should be cancelled in ``TIMEOUT`` seconds", even after the ``with trio.move_on_after(TIMEOUT):`` block is gone. The reason has to do with :ref:`how cancellation is implemented <cancellation>`. Recall that cancellation is represented by a `Cancelled` exception, which eventually needs to be caught by the cancel scope that caused it. (Otherwise, the exception would take down your whole program!) In order to be able to cancel the child tasks, the cancel scope has to be able to "see" the `Cancelled` exceptions that they raise -- and those exceptions come out of the ``async with open_nursery()`` block, not out of the call to ``start_soon()``.
723
724 If you want a timeout to apply to one task but not another, then you need to put the cancel scope in that individual task's function -- ``child()``, in this example.
725
726 .. _exceptiongroups:
727
728 Errors in multiple child tasks
729 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
730
731 Normally, in Python, only one thing happens at a time, which means
732 that only one thing can go wrong at a time. Trio has no such
733 limitation. Consider code like:
734
735 .. code-block:: python
736
737 async def broken1():
738 d = {}
739 return d["missing"]
740
741 async def broken2():
742 seq = range(10)
743 return seq[20]
744
745 async def parent():
746 async with trio.open_nursery() as nursery:
747 nursery.start_soon(broken1)
748 nursery.start_soon(broken2)
749
750 ``broken1`` raises ``KeyError``. ``broken2`` raises
751 ``IndexError``. Obviously ``parent`` should raise some error, but
752 what? The answer is that both exceptions are grouped in an :exc:`ExceptionGroup`.
753 :exc:`ExceptionGroup` and its parent class :exc:`BaseExceptionGroup` are used to
754 encapsulate multiple exceptions being raised at once.
755
756 To catch individual exceptions encapsulated in an exception group, the ``except*``
757 clause was introduced in Python 3.11 (:pep:`654`). Here's how it works:
758
759 .. code-block:: python
760
761 try:
762 async with trio.open_nursery() as nursery:
763 nursery.start_soon(broken1)
764 nursery.start_soon(broken2)
765 except* KeyError as excgroup:
766 for exc in excgroup.exceptions:
767 ... # handle each KeyError
768 except* IndexError as excgroup:
769 for exc in excgroup.exceptions:
770 ... # handle each IndexError
771
772 If you want to reraise exceptions, or raise new ones, you can do so, but be aware that
773 exceptions raised in ``except*`` sections will be raised together in a new exception
774 group.
775
776 But what if you can't use Python 3.11, and therefore ``except*``, just yet?
777 The same exceptiongroup_ library which backports `ExceptionGroup` also lets
778 you approximate this behavior with exception handler callbacks:
779
780 .. code-block:: python
781
782 from exceptiongroup import catch
783
784 def handle_keyerrors(excgroup):
785 for exc in excgroup.exceptions:
786 ... # handle each KeyError
787
788 def handle_indexerrors(excgroup):
789 for exc in excgroup.exceptions:
790 ... # handle each IndexError
791
792 with catch({
793 KeyError: handle_keyerrors,
794 IndexError: handle_indexerrors
795 }):
796 async with trio.open_nursery() as nursery:
797 nursery.start_soon(broken1)
798 nursery.start_soon(broken2)
799
800 The semantics for the handler functions are equal to ``except*`` blocks, except for
801 setting local variables. If you need to set local variables, you need to declare them
802 inside the handler function(s) with the ``nonlocal`` keyword:
803
804 .. code-block:: python
805
806 def handle_keyerrors(excgroup):
807 nonlocal myflag
808 myflag = True
809
810 myflag = False
811 with catch({KeyError: handle_keyerrors}):
812 async with trio.open_nursery() as nursery:
813 nursery.start_soon(broken1)
814
815 .. _handling_exception_groups:
816
817 Designing for multiple errors
818 +++++++++++++++++++++++++++++
819
820 Structured concurrency is still a relatively new design pattern, but there are a few
821 approaches we've identified for how you (or your users) might want to handle groups of
822 exceptions. Note that the final pattern, simply raising an `ExceptionGroup`, is the most
823 common - and nurseries automatically do that for you.
824
825 **First**, you might want to 'defer to' a particular exception type, raising just that if
826 there is any such instance in the group. For example: `KeyboardInterrupt` has a clear
827 meaning for the surrounding code, could reasonably take priority over errors of other
828 types, and whether you have one or several of them doesn't really matter.
829
830 This pattern can often be implemented using a decorator or a context manager, such
831 as :func:`trio_util.multi_error_defer_to` or :func:`trio_util.defer_to_cancelled`.
832 Note however that re-raising a 'leaf' exception will discard whatever part of the
833 traceback is attached to the `ExceptionGroup` itself, so we don't recommend this for
834 errors that will be presented to humans.
835
836 ..
837 TODO: what about `Cancelled`? It's relevantly similar to `KeyboardInterrupt`,
838 but if you have multiple Cancelleds destined for different scopes, it seems
839 like it might be bad to abandon all-but-one of those - we might try to execute
840 some more code which then itself gets cancelled again, and incur more cleanup.
841 That's only a mild inefficiency though, and the semantics are fine overall.
842
843 **Second**, you might want to treat the concurrency inside your code as an implementation
844 detail which is hidden from your users - for example, abstracting a protocol which
845 involves sending and receiving data to a simple receive-only interface, or implementing
846 a context manager which maintains some background tasks for the length of the
847 ``async with`` block.
848
849 The simple option here is to ``raise MySpecificError from group``, allowing users to
850 handle your library-specific error. This is simple and reliable, but doesn't completely
851 hide the nursery. *Do not* unwrap single exceptions if there could ever be multiple
852 exceptions though; that always ends in latent bugs and then tears.
853
854 The more complex option is to ensure that only one exception can in fact happen at a time.
855 This is *very hard*, for example you'll need to handle `KeyboardInterrupt` somehow, and
856 we strongly recommend having a ``raise PleaseReportBug from group`` fallback just in case
857 you get a group containing more than one exception.
858 This is useful when writing a context manager which starts some background tasks, and then
859 yields to user code which effectively runs 'inline' in the body of the nursery block.
860 In this case, the background tasks can be wrapped with e.g. the `outcome
861 <https://pypi.org/project/outcome/>`__ library to ensure that only one exception
862 can be raised (from end-user code); and then you can either ``raise SomeInternalError``
863 if a background task failed, or unwrap the user exception if that was the only error.
864
865 ..
866 For more on this pattern, see https://github.com/python-trio/trio/issues/2929
867 and the linked issue on trio-websocket. We may want to provide a nursery mode
868 which handles this automatically; it's annoying but not too complicated and
869 seems like it might be a good feature to ship for such cases.
870
871 **Third and most often**, the existence of a nursery in your code is not just an
872 implementation detail, and callers *should* be prepared to handle multiple exceptions
873 in the form of an `ExceptionGroup`, whether with ``except*`` or manual inspection
874 or by just letting it propagate to *their* callers. Because this is so common,
875 it's nurseries' default behavior and you don't need to do anything.
876
877 .. _strict_exception_groups:
878
879 Historical Note: "non-strict" ExceptionGroups
880 +++++++++++++++++++++++++++++++++++++++++++++
881
882 In early versions of Trio, the ``except*`` syntax hadn't be dreamt up yet, and we
883 hadn't worked with structured concurrency for long or in large codebases.
884 As a concession to convenience, some APIs would therefore raise single exceptions,
885 and only wrap concurrent exceptions in the old ``trio.MultiError`` type if there
886 were two or more.
887
888 Unfortunately, the results were not good: calling code often didn't realize that
889 some function *could* raise a ``MultiError``, and therefore handle only the common
890 case - with the result that things would work well in testing, and then crash under
891 heavier load (typically in production). `asyncio.TaskGroup` learned from this
892 experience and *always* wraps errors into an `ExceptionGroup`, as does ``anyio``,
893 and as of Trio 0.25 that's our default behavior too.
894
895 We currently support a compatibility argument ``strict_exception_groups=False`` to
896 `trio.run` and `trio.open_nursery`, which restores the old behavior (although
897 ``MultiError`` itself has been fully removed). We strongly advise against it for
898 new code, and encourage existing uses to migrate - we consider the option deprecated
899 and plan to remove it after a period of documented and then runtime warnings.
900
901 .. _exceptiongroup: https://pypi.org/project/exceptiongroup/
902
903 Spawning tasks without becoming a parent
904 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
905
906 Sometimes it doesn't make sense for the task that starts a child to
907 take on responsibility for watching it. For example, a server task may
908 want to start a new task for each connection, but it can't listen for
909 connections and supervise children at the same time.
910
911 The solution here is simple once you see it: there's no requirement
912 that a nursery object stay in the task that created it! We can write
913 code like this:
914
915 .. code-block:: python
916
917 async def new_connection_listener(handler, nursery):
918 while True:
919 conn = await get_new_connection()
920 nursery.start_soon(handler, conn)
921
922 async def server(handler):
923 async with trio.open_nursery() as nursery:
924 nursery.start_soon(new_connection_listener, handler, nursery)
925
926 Notice that ``server`` opens a nursery and passes it to
927 ``new_connection_listener``, and then ``new_connection_listener`` is
928 able to start new tasks as "siblings" of itself. Of course, in this
929 case, we could just as well have written:
930
931 .. code-block:: python
932
933 async def server(handler):
934 async with trio.open_nursery() as nursery:
935 while True:
936 conn = await get_new_connection()
937 nursery.start_soon(handler, conn)
938
939 \...but sometimes things aren't so simple, and this trick comes in
940 handy.
941
942 One thing to remember, though: cancel scopes are inherited from the
943 nursery, **not** from the task that calls ``start_soon``. So in this
944 example, the timeout does *not* apply to ``child`` (or to anything
945 else):
946
947 .. code-block:: python
948
949 async def do_spawn(nursery):
950 with trio.move_on_after(TIMEOUT): # don't do this, it has no effect
951 nursery.start_soon(child)
952
953 async with trio.open_nursery() as nursery:
954 nursery.start_soon(do_spawn, nursery)
955
956
957 Custom supervisors
958 ~~~~~~~~~~~~~~~~~~
959
960 The default cleanup logic is often sufficient for simple cases, but
961 what if you want a more sophisticated supervisor? For example, maybe
962 you have `Erlang envy <http://learnyousomeerlang.com/supervisors>`__
963 and want features like automatic restart of crashed tasks. Trio itself
964 doesn't provide these kinds of features, but you can build them on
965 top; Trio's goal is to enforce basic hygiene and then get out of your
966 way. (Specifically: Trio won't let you build a supervisor that exits
967 and leaves orphaned tasks behind, and if you have an unhandled
968 exception due to bugs or laziness then Trio will make sure they
969 propagate.) And then you can wrap your fancy supervisor up in a
970 library and put it on PyPI, because supervisors are tricky and there's
971 no reason everyone should have to write their own.
972
973 For example, here's a function that takes a list of functions, runs
974 them all concurrently, and returns the result from the one that
975 finishes first:
976
977 .. code-block:: python
978
979 async def race(*async_fns):
980 if not async_fns:
981 raise ValueError("must pass at least one argument")
982
983 winner = None
984
985 async def jockey(async_fn, cancel_scope):
986 nonlocal winner
987 winner = await async_fn()
988 cancel_scope.cancel()
989
990 async with trio.open_nursery() as nursery:
991 for async_fn in async_fns:
992 nursery.start_soon(jockey, async_fn, nursery.cancel_scope)
993
994 return winner
995
996 This works by starting a set of tasks which each try to run their
997 function. As soon as the first function completes its execution, the task will set the nonlocal variable ``winner``
998 from the outer scope to the result of the function, and cancel the other tasks using the passed in cancel scope. Once all tasks
999 have been cancelled (which exits the nursery block), the variable ``winner`` will be returned.
1000
1001 Here if one or more of the racing functions raises an unhandled
1002 exception then Trio's normal handling kicks in: it cancels the others
1003 and then propagates the exception. If you want different behavior, you
1004 can get that by adding a ``try`` block to the ``jockey`` function to
1005 catch exceptions and handle them however you like.
1006
1007
1008 Task-related API details
1009 ~~~~~~~~~~~~~~~~~~~~~~~~
1010
1011 The nursery API
1012 +++++++++++++++
1013
1014 .. autofunction:: open_nursery
1015 :async-with: nursery
1016
1017
1018 .. autoclass:: Nursery()
1019 :members: child_tasks, parent_task
1020
1021 .. automethod:: start(async_fn, *args, name = None)
1022
1023 .. automethod:: start_soon(async_fn, *args, name = None)
1024
1025 .. attribute:: TASK_STATUS_IGNORED
1026 :type: TaskStatus
1027
1028 See :meth:`Nursery.start`.
1029
1030 .. autoclass:: TaskStatus(Protocol[StatusT])
1031 :members:
1032
1033 .. _task-local-storage:
1034
1035 Task-local storage
1036 ------------------
1037
1038 Suppose you're writing a server that responds to network requests, and
1039 you log some information about each request as you process it. If the
1040 server is busy and there are multiple requests being handled at the
1041 same time, then you might end up with logs like this:
1042
1043 .. code-block:: none
1044
1045 Request handler started
1046 Request handler started
1047 Request handler finished
1048 Request handler finished
1049
1050 In this log, it's hard to know which lines came from which
1051 request. (Did the request that started first also finish first, or
1052 not?) One way to solve this is to assign each request a unique
1053 identifier, and then include this identifier in each log message:
1054
1055 .. code-block:: none
1056
1057 request 1: Request handler started
1058 request 2: Request handler started
1059 request 2: Request handler finished
1060 request 1: Request handler finished
1061
1062 This way we can see that request 1 was slow: it started before request
1063 2 but finished afterwards. (You can also get `much fancier
1064 <https://opentracing.io/docs/>`__, but this is enough for an
1065 example.)
1066
1067 Now, here's the problem: how does the logging code know what the
1068 request identifier is? One approach would be to explicitly pass it
1069 around to every function that might want to emit logs... but that's
1070 basically every function, because you never know when you might need
1071 to add a ``log.debug(...)`` call to some utility function buried deep
1072 in the call stack, and when you're in the middle of a debugging a
1073 nasty problem that last thing you want is to have to stop first and
1074 refactor everything to pass through the request identifier! Sometimes
1075 this is the right solution, but other times it would be much more
1076 convenient if we could store the identifier in a global variable, so
1077 that the logging function could look it up whenever it needed
1078 it. Except... a global variable can only have one value at a time, so
1079 if we have multiple handlers running at once then this isn't going to
1080 work. What we need is something that's *like* a global variable, but
1081 that can have different values depending on which request handler is
1082 accessing it.
1083
1084 To solve this problem, Python has a module in the standard
1085 library: :mod:`contextvars`.
1086
1087 Here's a toy example demonstrating how to use :mod:`contextvars`:
1088
1089 .. literalinclude:: reference-core/contextvar-example.py
1090
1091 Example output (yours may differ slightly):
1092
1093 .. code-block:: none
1094
1095 request 1: Request handler started
1096 request 2: Request handler started
1097 request 0: Request handler started
1098 request 2: Helper task a started
1099 request 2: Helper task b started
1100 request 1: Helper task a started
1101 request 1: Helper task b started
1102 request 0: Helper task b started
1103 request 0: Helper task a started
1104 request 2: Helper task b finished
1105 request 2: Helper task a finished
1106 request 2: Request received finished
1107 request 0: Helper task a finished
1108 request 1: Helper task a finished
1109 request 1: Helper task b finished
1110 request 1: Request received finished
1111 request 0: Helper task b finished
1112 request 0: Request received finished
1113
1114 For more information, read the
1115 `contextvars docs <https://docs.python.org/3/library/contextvars.html>`__.
1116
1117
1118 .. _synchronization:
1119
1120 Synchronizing and communicating between tasks
1121 ---------------------------------------------
1122
1123 Trio provides a standard set of synchronization and inter-task
1124 communication primitives. These objects' APIs are generally modelled
1125 off of the analogous classes in the standard library, but with some
1126 differences.
1127
1128
1129 Blocking and non-blocking methods
1130 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1131
1132 The standard library synchronization primitives have a variety of
1133 mechanisms for specifying timeouts and blocking behavior, and of
1134 signaling whether an operation returned due to success versus a
1135 timeout.
1136
1137 In Trio, we standardize on the following conventions:
1138
1139 * We don't provide timeout arguments. If you want a timeout, then use
1140 a cancel scope.
1141
1142 * For operations that have a non-blocking variant, the blocking and
1143 non-blocking variants are different methods with names like ``X``
1144 and ``X_nowait``, respectively. (This is similar to
1145 :class:`queue.Queue`, but unlike most of the classes in
1146 :mod:`threading`.) We like this approach because it allows us to
1147 make the blocking version async and the non-blocking version sync.
1148
1149 * When a non-blocking method cannot succeed (the channel is empty, the
1150 lock is already held, etc.), then it raises :exc:`trio.WouldBlock`.
1151 There's no equivalent to the :exc:`queue.Empty` versus
1152 :exc:`queue.Full` distinction – we just have the one exception that
1153 we use consistently.
1154
1155
1156 Fairness
1157 ~~~~~~~~
1158
1159 These classes are all guaranteed to be "fair", meaning that when it
1160 comes time to choose who will be next to acquire a lock, get an item
1161 from a queue, etc., then it always goes to the task which has been
1162 waiting longest. It's `not entirely clear
1163 <https://github.com/python-trio/trio/issues/54>`__ whether this is the
1164 best choice, but for now that's how it works.
1165
1166 As an example of what this means, here's a small program in which two
1167 tasks compete for a lock. Notice that the task which releases the lock
1168 always immediately attempts to re-acquire it, before the other task has
1169 a chance to run. (And remember that we're doing cooperative
1170 multi-tasking here, so it's actually *deterministic* that the task
1171 releasing the lock will call :meth:`~Lock.acquire` before the other
1172 task wakes up; in Trio releasing a lock is not a checkpoint.) With
1173 an unfair lock, this would result in the same task holding the lock
1174 forever and the other task being starved out. But if you run this,
1175 you'll see that the two tasks politely take turns:
1176
1177 .. code-block:: python
1178
1179 # fairness-demo.py
1180
1181 import trio
1182
1183 async def loopy_child(number, lock):
1184 while True:
1185 async with lock:
1186 print(f"Child {number} has the lock!")
1187 await trio.sleep(0.5)
1188
1189 async def main():
1190 async with trio.open_nursery() as nursery:
1191 lock = trio.Lock()
1192 nursery.start_soon(loopy_child, 1, lock)
1193 nursery.start_soon(loopy_child, 2, lock)
1194
1195 trio.run(main)
1196
1197
1198 Broadcasting an event with :class:`Event`
1199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1200
1201 .. autoclass:: Event
1202 :members:
1203
1204 .. autoclass:: EventStatistics
1205 :members:
1206
1207 .. _channels:
1208
1209 Using channels to pass values between tasks
1210 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1211
1212 *Channels* allow you to safely and conveniently send objects between
1213 different tasks. They're particularly useful for implementing
1214 producer/consumer patterns.
1215
1216 The core channel API is defined by the abstract base classes
1217 :class:`trio.abc.SendChannel` and :class:`trio.abc.ReceiveChannel`.
1218 You can use these to implement your own custom channels, that do
1219 things like pass objects between processes or over the network. But in
1220 many cases, you just want to pass objects between different tasks
1221 inside a single process, and for that you can use
1222 :func:`trio.open_memory_channel`:
1223
1224 .. autofunction:: open_memory_channel(max_buffer_size)
1225
1226 .. note:: If you've used the :mod:`threading` or :mod:`asyncio`
1227 modules, you may be familiar with :class:`queue.Queue` or
1228 :class:`asyncio.Queue`. In Trio, :func:`open_memory_channel` is
1229 what you use when you're looking for a queue. The main difference
1230 is that Trio splits the classic queue interface up into two
1231 objects. The advantage of this is that it makes it possible to put
1232 the two ends in different processes without rewriting your code,
1233 and that we can close the two sides separately.
1234
1235 `MemorySendChannel` and `MemoryReceiveChannel` also expose several
1236 more features beyond the core channel interface:
1237
1238 .. autoclass:: MemorySendChannel
1239 :members:
1240
1241 .. autoclass:: MemoryReceiveChannel
1242 :members:
1243
1244 .. autoclass:: MemoryChannelStatistics
1245 :members:
1246
1247 A simple channel example
1248 ++++++++++++++++++++++++
1249
1250 Here's a simple example of how to use memory channels:
1251
1252 .. literalinclude:: reference-core/channels-simple.py
1253
1254 If you run this, it prints:
1255
1256 .. code-block:: none
1257
1258 got value "message 0"
1259 got value "message 1"
1260 got value "message 2"
1261
1262 And then it hangs forever. (Use control-C to quit.)
1263
1264
1265 .. _channel-shutdown:
1266
1267 Clean shutdown with channels
1268 ++++++++++++++++++++++++++++
1269
1270 Of course we don't generally like it when programs hang. What
1271 happened? The problem is that the producer sent 3 messages and then
1272 exited, but the consumer has no way to tell that the producer is gone:
1273 for all it knows, another message might be coming along any moment. So
1274 it hangs forever waiting for the 4th message.
1275
1276 Here's a new version that fixes this: it produces the same output as
1277 the previous version, and then exits cleanly. The only change is the
1278 addition of ``async with`` blocks inside the producer and consumer:
1279
1280 .. literalinclude:: reference-core/channels-shutdown.py
1281 :emphasize-lines: 12,18
1282
1283 The really important thing here is the producer's ``async with`` .
1284 When the producer exits, this closes the ``send_channel``, and that
1285 tells the consumer that no more messages are coming, so it can cleanly
1286 exit its ``async for`` loop. Then the program shuts down because both
1287 tasks have exited.
1288
1289 We also added an ``async with`` to the consumer. This isn't as
1290 important, but it can help us catch mistakes or other problems. For
1291 example, suppose that the consumer exited early for some reason –
1292 maybe because of a bug. Then the producer would be sending messages
1293 into the void, and might get stuck indefinitely. But, if the consumer
1294 closes its ``receive_channel``, then the producer will get a
1295 :exc:`BrokenResourceError` to alert it that it should stop sending
1296 messages because no-one is listening.
1297
1298 If you want to see the effect of the consumer exiting early, try
1299 adding a ``break`` statement to the ``async for`` loop – you should
1300 see a :exc:`BrokenResourceError` from the producer.
1301
1302
1303 .. _channel-mpmc:
1304
1305 Managing multiple producers and/or multiple consumers
1306 +++++++++++++++++++++++++++++++++++++++++++++++++++++
1307
1308 You can also have multiple producers, and multiple consumers, all
1309 sharing the same channel. However, this makes shutdown a little more
1310 complicated.
1311
1312 For example, consider this naive extension of our previous example,
1313 now with two producers and two consumers:
1314
1315 .. literalinclude:: reference-core/channels-mpmc-broken.py
1316
1317 The two producers, A and B, send 3 messages apiece. These are then
1318 randomly distributed between the two consumers, X and Y. So we're
1319 hoping to see some output like:
1320
1321 .. code-block:: none
1322
1323 consumer Y got value '0 from producer B'
1324 consumer X got value '0 from producer A'
1325 consumer Y got value '1 from producer A'
1326 consumer Y got value '1 from producer B'
1327 consumer X got value '2 from producer B'
1328 consumer X got value '2 from producer A'
1329
1330 However, on most runs, that's not what happens – the first part of the
1331 output is OK, and then when we get to the end the program crashes with
1332 :exc:`ClosedResourceError`. If you run the program a few times, you'll
1333 see that sometimes the traceback shows ``send`` crashing, and other
1334 times it shows ``receive`` crashing, and you might even find that on
1335 some runs it doesn't crash at all.
1336
1337 Here's what's happening: suppose that producer A finishes first. It
1338 exits, and its ``async with`` block closes the ``send_channel``. But
1339 wait! Producer B was still using that ``send_channel``... so the next
1340 time B calls ``send``, it gets a :exc:`ClosedResourceError`.
1341
1342 Sometimes, though if we're lucky, the two producers might finish at
1343 the same time (or close enough), so they both make their last ``send``
1344 before either of them closes the ``send_channel``.
1345
1346 But, even if that happens, we're not out of the woods yet! After the
1347 producers exit, the two consumers race to be the first to notice that
1348 the ``send_channel`` has closed. Suppose that X wins the race. It
1349 exits its ``async for`` loop, then exits the ``async with`` block...
1350 and closes the ``receive_channel``, while Y is still using it. Again,
1351 this causes a crash.
1352
1353 We could avoid this by using some complicated bookkeeping to make sure
1354 that only the *last* producer and the *last* consumer close their
1355 channel endpoints... but that would be tiresome and fragile.
1356 Fortunately, there's a better way! Here's a fixed version of our
1357 program above:
1358
1359 .. literalinclude:: reference-core/channels-mpmc-fixed.py
1360 :emphasize-lines: 8, 10, 11, 13, 14
1361
1362 This example demonstrates using the `MemorySendChannel.clone` and
1363 `MemoryReceiveChannel.clone` methods. What these do is create copies
1364 of our endpoints, that act just like the original – except that they
1365 can be closed independently. And the underlying channel is only closed
1366 after *all* the clones have been closed. So this completely solves our
1367 problem with shutdown, and if you run this program, you'll see it
1368 print its six lines of output and then exits cleanly.
1369
1370 Notice a small trick we use: the code in ``main`` creates clone
1371 objects to pass into all the child tasks, and then closes the original
1372 objects using ``async with``. Another option is to pass clones into
1373 all-but-one of the child tasks, and then pass the original object into
1374 the last task, like:
1375
1376 .. code-block:: python
1377
1378 # Also works, but is more finicky:
1379 send_channel, receive_channel = trio.open_memory_channel(0)
1380 nursery.start_soon(producer, "A", send_channel.clone())
1381 nursery.start_soon(producer, "B", send_channel)
1382 nursery.start_soon(consumer, "X", receive_channel.clone())
1383 nursery.start_soon(consumer, "Y", receive_channel)
1384
1385 But this is more error-prone, especially if you use a loop to spawn
1386 the producers/consumers.
1387
1388 Just make sure that you don't write:
1389
1390 .. code-block:: python
1391
1392 # Broken, will cause program to hang:
1393 send_channel, receive_channel = trio.open_memory_channel(0)
1394 nursery.start_soon(producer, "A", send_channel.clone())
1395 nursery.start_soon(producer, "B", send_channel.clone())
1396 nursery.start_soon(consumer, "X", receive_channel.clone())
1397 nursery.start_soon(consumer, "Y", receive_channel.clone())
1398
1399 Here we pass clones into the tasks, but never close the original
1400 objects. That means we have 3 send channel objects (the original + two
1401 clones), but we only close 2 of them, so the consumers will hang
1402 around forever waiting for that last one to be closed.
1403
1404
1405 .. _channel-buffering:
1406
1407 Buffering in channels
1408 +++++++++++++++++++++
1409
1410 When you call :func:`open_memory_channel`, you have to specify how
1411 many values can be buffered internally in the channel. If the buffer
1412 is full, then any task that calls :meth:`~trio.abc.SendChannel.send`
1413 will stop and wait for another task to call
1414 :meth:`~trio.abc.ReceiveChannel.receive`. This is useful because it
1415 produces *backpressure*: if the channel producers are running faster
1416 than the consumers, then it forces the producers to slow down.
1417
1418 You can disable buffering entirely, by doing
1419 ``open_memory_channel(0)``. In that case any task that calls
1420 :meth:`~trio.abc.SendChannel.send` will wait until another task calls
1421 :meth:`~trio.abc.ReceiveChannel.receive`, and vice versa. This is similar to
1422 how channels work in the `classic Communicating Sequential Processes
1423 model <https://en.wikipedia.org/wiki/Channel_(programming)>`__, and is
1424 a reasonable default if you aren't sure what size buffer to use.
1425 (That's why we used it in the examples above.)
1426
1427 At the other extreme, you can make the buffer unbounded by using
1428 ``open_memory_channel(math.inf)``. In this case,
1429 :meth:`~trio.abc.SendChannel.send` *always* returns immediately.
1430 Normally, this is a bad idea. To see why, consider a program where the
1431 producer runs more quickly than the consumer:
1432
1433 .. literalinclude:: reference-core/channels-backpressure.py
1434
1435 If you run this program, you'll see output like:
1436
1437 .. code-block:: none
1438
1439 Sent message: 0
1440 Received message: 0
1441 Sent message: 1
1442 Sent message: 2
1443 Sent message: 3
1444 Sent message: 4
1445 Sent message: 5
1446 Sent message: 6
1447 Sent message: 7
1448 Sent message: 8
1449 Sent message: 9
1450 Received message: 1
1451 Sent message: 10
1452 Sent message: 11
1453 Sent message: 12
1454 ...
1455
1456 On average, the producer sends ten messages per second, but the
1457 consumer only calls ``receive`` once per second. That means that each
1458 second, the channel's internal buffer has to grow to hold an extra
1459 nine items. After a minute, the buffer will have ~540 items in it;
1460 after an hour, that grows to ~32,400. Eventually, the program will run
1461 out of memory. And well before we run out of memory, our latency on
1462 handling individual messages will become abysmal. For example, at the
1463 one minute mark, the producer is sending message ~600, but the
1464 consumer is still processing message ~60. Message 600 will have to sit
1465 in the channel for ~9 minutes before the consumer catches up and
1466 processes it.
1467
1468 Now try replacing ``open_memory_channel(math.inf)`` with
1469 ``open_memory_channel(0)``, and run it again. We get output like:
1470
1471 .. code-block:: none
1472
1473 Sent message: 0
1474 Received message: 0
1475 Received message: 1
1476 Sent message: 1
1477 Received message: 2
1478 Sent message: 2
1479 Sent message: 3
1480 Received message: 3
1481 ...
1482
1483 Now the ``send`` calls wait for the ``receive`` calls to finish, which
1484 forces the producer to slow down to match the consumer's speed. (It
1485 might look strange that some values are reported as "Received" before
1486 they're reported as "Sent"; this happens because the actual
1487 send/receive happen at the same time, so which line gets printed first
1488 is random.)
1489
1490 Now, let's try setting a small but nonzero buffer size, like
1491 ``open_memory_channel(3)``. what do you think will happen?
1492
1493 I get:
1494
1495 .. code-block:: none
1496
1497 Sent message: 0
1498 Received message: 0
1499 Sent message: 1
1500 Sent message: 2
1501 Sent message: 3
1502 Received message: 1
1503 Sent message: 4
1504 Received message: 2
1505 Sent message: 5
1506 ...
1507
1508 So you can see that the producer runs ahead by 3 messages, and then
1509 stops to wait: when the consumer reads message 1, it sends message 4,
1510 then when the consumer reads message 2, it sends message 5, and so on.
1511 Once it reaches the steady state, this version acts just like our
1512 previous version where we set the buffer size to 0, except that it
1513 uses a bit more memory and each message sits in the buffer for a bit
1514 longer before being processed (i.e., the message latency is higher).
1515
1516 Of course real producers and consumers are usually more complicated
1517 than this, and in some situations, a modest amount of buffering might
1518 improve throughput. But too much buffering wastes memory and increases
1519 latency, so if you want to tune your application you should experiment
1520 to see what value works best for you.
1521
1522 **Why do we even support unbounded buffers then?** Good question!
1523 Despite everything we saw above, there are times when you actually do
1524 need an unbounded buffer. For example, consider a web crawler that
1525 uses a channel to keep track of all the URLs it still wants to crawl.
1526 Each crawler runs a loop where it takes a URL from the channel,
1527 fetches it, checks the HTML for outgoing links, and then adds the new
1528 URLs to the channel. This creates a *circular flow*, where each
1529 consumer is also a producer. In this case, if your channel buffer gets
1530 full, then the crawlers will block when they try to add new URLs to
1531 the channel, and if all the crawlers got blocked, then they aren't
1532 taking any URLs out of the channel, so they're stuck forever in a
1533 deadlock. Using an unbounded channel avoids this, because it means
1534 that :meth:`~trio.abc.SendChannel.send` never blocks.
1535
1536
1537 Lower-level synchronization primitives
1538 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1539
1540 Personally, I find that events and channels are usually enough to
1541 implement most things I care about, and lead to easier to read code
1542 than the lower-level primitives discussed in this section. But if you
1543 need them, they're here. (If you find yourself reaching for these
1544 because you're trying to implement a new higher-level synchronization
1545 primitive, then you might also want to check out the facilities in
1546 :mod:`trio.lowlevel` for a more direct exposure of Trio's underlying
1547 synchronization logic. All of classes discussed in this section are
1548 implemented on top of the public APIs in :mod:`trio.lowlevel`; they
1549 don't have any special access to Trio's internals.)
1550
1551 .. autoclass:: CapacityLimiter
1552 :members:
1553
1554 .. autoclass:: Semaphore
1555 :members:
1556
1557 .. We have to use :inherited-members: here because all the actual lock
1558 methods are stashed in _LockImpl. Weird side-effect of having both
1559 Lock and StrictFIFOLock, but wanting both to be marked Final so
1560 neither can inherit from the other.
1561
1562 .. autoclass:: Lock
1563 :members:
1564 :inherited-members:
1565
1566 .. autoclass:: StrictFIFOLock
1567 :members:
1568
1569 .. autoclass:: Condition
1570 :members:
1571
1572 These primitives return statistics objects that can be inspected.
1573
1574 .. autoclass:: CapacityLimiterStatistics
1575 :members:
1576
1577 .. autoclass:: LockStatistics
1578 :members:
1579
1580 .. autoclass:: ConditionStatistics
1581 :members:
1582
1583 .. _async-generators:
1584
1585 Notes on async generators
1586 -------------------------
1587
1588 Python 3.6 added support for *async generators*, which can use
1589 ``await``, ``async for``, and ``async with`` in between their ``yield``
1590 statements. As you might expect, you use ``async for`` to iterate
1591 over them. :pep:`525` has many more details if you want them.
1592
1593 For example, the following is a roundabout way to print
1594 the numbers 0 through 9 with a 1-second delay before each one:
1595
1596 .. code-block:: python
1597
1598 async def range_slowly(*args):
1599 """Like range(), but adds a 1-second sleep before each value."""
1600 for value in range(*args):
1601 await trio.sleep(1)
1602 yield value
1603
1604 async def use_it():
1605 async for value in range_slowly(10):
1606 print(value)
1607
1608 trio.run(use_it)
1609
1610 Trio supports async generators, but there's several caveats and it's very
1611 hard to handle them properly. Therefore Trio bundles a helper,
1612 `trio.as_safe_channel` that does it for you.
1613
1614
1615 .. autofunction:: trio.as_safe_channel
1616
1617 The details behind the problems are described in the following sections.
1618
1619 Finalization
1620 ~~~~~~~~~~~~
1621
1622 If you iterate over an async generator in its entirety, like the
1623 example above does, then the execution of the async generator will
1624 occur completely in the context of the code that's iterating over it,
1625 and there aren't too many surprises.
1626
1627 If you abandon a partially-completed async generator, though, such as
1628 by ``break``\ing out of the iteration, things aren't so simple. The
1629 async generator iterator object is still alive, waiting for you to
1630 resume iterating it so it can produce more values. At some point,
1631 Python will realize that you've dropped all references to the
1632 iterator, and will call on Trio to throw in a `GeneratorExit` exception
1633 so that any remaining cleanup code inside the generator has a chance
1634 to run: ``finally`` blocks, ``__aexit__`` handlers, and so on.
1635
1636 So far, so good. Unfortunately, Python provides no guarantees about
1637 *when* this happens. It could be as soon as you break out of the
1638 ``async for`` loop, or an arbitrary amount of time later. It could
1639 even be after the entire Trio run has finished! Just about the only
1640 guarantee is that it *won't* happen in the task that was using the
1641 generator. That task will continue on with whatever else it's doing,
1642 and the async generator cleanup will happen "sometime later,
1643 somewhere else": potentially with different context variables,
1644 not subject to timeouts, and/or after any nurseries you're using have
1645 been closed.
1646
1647 If you don't like that ambiguity, and you want to ensure that a
1648 generator's ``finally`` blocks and ``__aexit__`` handlers execute as
1649 soon as you're done using it, then you'll need to wrap your use of the
1650 generator in something like `async_generator.aclosing()
1651 <https://async-generator.readthedocs.io/en/latest/reference.html#context-managers>`__:
1652
1653 .. code-block:: python
1654
1655 # Instead of this:
1656 async for value in my_generator():
1657 if value == 42:
1658 break
1659
1660 # Do this:
1661 async with aclosing(my_generator()) as aiter:
1662 async for value in aiter:
1663 if value == 42:
1664 break
1665
1666 This is cumbersome, but Python unfortunately doesn't provide any other
1667 reliable options. If you use ``aclosing()``, then
1668 your generator's cleanup code executes in the same context as the
1669 rest of its iterations, so timeouts, exceptions, and context
1670 variables work like you'd expect.
1671
1672 If you don't use ``aclosing()``, then Trio will do
1673 its best anyway, but you'll have to contend with the following semantics:
1674
1675 * The cleanup of the generator occurs in a cancelled context, i.e.,
1676 all blocking calls executed during cleanup will raise `Cancelled`.
1677 This is to compensate for the fact that any timeouts surrounding
1678 the original use of the generator have been long since forgotten.
1679
1680 * The cleanup runs without access to any :ref:`context variables
1681 <task-local-storage>` that may have been present when the generator
1682 was originally being used.
1683
1684 * If the generator raises an exception during cleanup, then it's
1685 printed to the ``trio.async_generator_errors`` logger and otherwise
1686 ignored.
1687
1688 * If an async generator is still alive at the end of the whole
1689 call to :func:`trio.run`, then it will be cleaned up after all
1690 tasks have exited and before :func:`trio.run` returns.
1691 Since the "system nursery" has already been closed at this point,
1692 Trio isn't able to support any new calls to
1693 :func:`trio.lowlevel.spawn_system_task`.
1694
1695 If you plan to run your code on PyPy to take advantage of its better
1696 performance, you should be aware that PyPy is *far more likely* than
1697 CPython to perform async generator cleanup at a time well after the
1698 last use of the generator. (This is a consequence of the fact that
1699 PyPy does not use reference counting to manage memory.) To help catch
1700 issues like this, Trio will issue a `ResourceWarning` (ignored by
1701 default, but enabled when running under ``python -X dev`` for example)
1702 for each async generator that needs to be handled through the fallback
1703 finalization path.
1704
1705 Cancel scopes and nurseries
1706 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1707
1708 .. warning:: You may not write a ``yield`` statement that suspends an async generator
1709 inside a `CancelScope` or `Nursery` that was entered within the generator.
1710
1711 That is, this is OK:
1712
1713 .. code-block:: python
1714
1715 async def some_agen():
1716 with trio.move_on_after(1):
1717 await long_operation()
1718 yield "first"
1719 async with trio.open_nursery() as nursery:
1720 nursery.start_soon(task1)
1721 nursery.start_soon(task2)
1722 yield "second"
1723 ...
1724
1725 But this is not:
1726
1727 .. code-block:: python
1728
1729 async def some_agen():
1730 with trio.move_on_after(1):
1731 yield "first"
1732 async with trio.open_nursery() as nursery:
1733 yield "second"
1734 ...
1735
1736 Async generators decorated with ``@asynccontextmanager`` to serve as
1737 the template for an async context manager are *not* subject to this
1738 constraint, because ``@asynccontextmanager`` uses them in a limited
1739 way that doesn't create problems.
1740
1741 Violating the rule described in this section will sometimes get you a
1742 useful error message, but Trio is not able to detect all such cases,
1743 so sometimes you'll get an unhelpful `TrioInternalError`. (And
1744 sometimes it will seem to work, which is probably the worst outcome of
1745 all, since then you might not notice the issue until you perform some
1746 minor refactoring of the generator or the code that's iterating it, or
1747 just get unlucky. There is a draft :pep:`789` with accompanying
1748 `discussion thread
1749 <https://discuss.python.org/t/preventing-yield-inside-certain-context-managers/1091>`__
1750 that would at least make it fail consistently.)
1751
1752 The reason for the restriction on cancel scopes has to do with the
1753 difficulty of noticing when a generator gets suspended and
1754 resumed. The cancel scopes inside the generator shouldn't affect code
1755 running outside the generator, but Trio isn't involved in the process
1756 of exiting and reentering the generator, so it would be hard pressed
1757 to keep its cancellation plumbing in the correct state. Nurseries
1758 use a cancel scope internally, so they have all the problems of cancel
1759 scopes plus a number of problems of their own: for example, when
1760 the generator is suspended, what should the background tasks do?
1761 There's no good way to suspend them, but if they keep running and throw
1762 an exception, where can that exception be reraised?
1763
1764 For more discussion, see
1765 Trio issues `264 <https://github.com/python-trio/trio/issues/264>`__
1766 (especially `this comment
1767 <https://github.com/python-trio/trio/issues/264#issuecomment-418989328>`__)
1768 and `638 <https://github.com/python-trio/trio/issues/638>`__.
1769
1770
1771 .. _threads:
1772
1773 Threads (if you must)
1774 ---------------------
1775
1776 In a perfect world, all third-party libraries and low-level APIs would
1777 be natively async and integrated into Trio, and all would be happiness
1778 and rainbows.
1779
1780 That world, alas, does not (yet) exist. Until it does, you may find
1781 yourself needing to interact with non-Trio APIs that do rude things
1782 like "blocking".
1783
1784 In acknowledgment of this reality, Trio provides two useful utilities
1785 for working with real, operating-system level,
1786 :mod:`threading`\-module-style threads. First, if you're in Trio but
1787 need to push some blocking I/O into a thread, there's
1788 `trio.to_thread.run_sync`. And if you're in a thread and need
1789 to communicate back with Trio, you can use
1790 :func:`trio.from_thread.run` and :func:`trio.from_thread.run_sync`.
1791
1792
1793 .. _worker-thread-limiting:
1794
1795 Trio's philosophy about managing worker threads
1796 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1797
1798 If you've used other I/O frameworks, you may have encountered the
1799 concept of a "thread pool", which is most commonly implemented as a
1800 fixed size collection of threads that hang around waiting for jobs to
1801 be assigned to them. These solve two different problems: First,
1802 reusing the same threads over and over is more efficient than
1803 starting and stopping a new thread for every job you need done;
1804 basically, the pool acts as a kind of cache for idle threads. And
1805 second, having a fixed size avoids getting into a situation where
1806 100,000 jobs are submitted simultaneously, and then 100,000 threads
1807 are spawned and the system gets overloaded and crashes. Instead, the N
1808 threads start executing the first N jobs, while the other
1809 (100,000 - N) jobs sit in a queue and wait their turn. Which is
1810 generally what you want, and this is how
1811 :func:`trio.to_thread.run_sync` works by default.
1812
1813 The downside of this kind of thread pool is that sometimes, you need
1814 more sophisticated logic for controlling how many threads are run at
1815 once. For example, you might want a policy like "at most 20 threads
1816 total, but no more than 3 of those can be running jobs associated with
1817 the same user account", or you might want a pool whose size is
1818 dynamically adjusted over time in response to system conditions.
1819
1820 It's even possible for a fixed-size policy to cause unexpected
1821 `deadlocks <https://en.wikipedia.org/wiki/Deadlock>`__. Imagine a
1822 situation where we have two different types of blocking jobs that you
1823 want to run in the thread pool, type A and type B. Type A is pretty
1824 simple: it just runs and completes pretty quickly. But type B is more
1825 complicated: it has to stop in the middle and wait for some other work
1826 to finish, and that other work includes running a type A job. Now,
1827 suppose you submit N jobs of type B to the pool. They all start
1828 running, and then eventually end up submitting one or more jobs of
1829 type A. But since every thread in our pool is already busy, the type A
1830 jobs don't actually start running – they just sit in a queue waiting
1831 for the type B jobs to finish. But the type B jobs will never finish,
1832 because they're waiting for the type A jobs. Our system has
1833 deadlocked. The ideal solution to this problem is to avoid having type
1834 B jobs in the first place – generally it's better to keep complex
1835 synchronization logic in the main Trio thread. But if you can't do
1836 that, then you need a custom thread allocation policy that tracks
1837 separate limits for different types of jobs, and make it impossible
1838 for type B jobs to fill up all the slots that type A jobs need to run.
1839
1840 So, we can see that it's important to be able to change the policy
1841 controlling the allocation of threads to jobs. But in many frameworks,
1842 this requires implementing a new thread pool from scratch, which is
1843 highly non-trivial; and if different types of jobs need different
1844 policies, then you may have to create multiple pools, which is
1845 inefficient because now you effectively have two different thread
1846 caches that aren't sharing resources.
1847
1848 Trio's solution to this problem is to split worker thread management
1849 into two layers. The lower layer is responsible for taking blocking
1850 I/O jobs and arranging for them to run immediately on some worker
1851 thread. It takes care of solving the tricky concurrency problems
1852 involved in managing threads and is responsible for optimizations like
1853 reusing threads, but has no admission control policy: if you give it
1854 100,000 jobs, it will spawn 100,000 threads. The upper layer is
1855 responsible for providing the policy to make sure that this doesn't
1856 happen – but since it *only* has to worry about policy, it can be much
1857 simpler. In fact, all there is to it is the ``limiter=`` argument
1858 passed to :func:`trio.to_thread.run_sync`. This defaults to a global
1859 :class:`CapacityLimiter` object, which gives us the classic fixed-size
1860 thread pool behavior. (See
1861 :func:`trio.to_thread.current_default_thread_limiter`.) But if you
1862 want to use "separate pools" for type A jobs and type B jobs, then
1863 it's just a matter of creating two separate :class:`CapacityLimiter`
1864 objects and passing them in when running these jobs. Or here's an
1865 example of defining a custom policy that respects the global thread
1866 limit, while making sure that no individual user can use more than 3
1867 threads at a time:
1868
1869 .. code-block:: python
1870
1871 class CombinedLimiter:
1872 def __init__(self, first, second):
1873 self._first = first
1874 self._second = second
1875
1876 async def acquire_on_behalf_of(self, borrower):
1877 # Acquire both, being careful to clean up properly on error
1878 await self._first.acquire_on_behalf_of(borrower)
1879 try:
1880 await self._second.acquire_on_behalf_of(borrower)
1881 except:
1882 self._first.release_on_behalf_of(borrower)
1883 raise
1884
1885 def release_on_behalf_of(self, borrower):
1886 # Release both, being careful to clean up properly on error
1887 try:
1888 self._second.release_on_behalf_of(borrower)
1889 finally:
1890 self._first.release_on_behalf_of(borrower)
1891
1892
1893 # Use a weak value dictionary, so that we don't waste memory holding
1894 # limiter objects for users who don't have any worker threads running.
1895 USER_LIMITERS = weakref.WeakValueDictionary()
1896 MAX_THREADS_PER_USER = 3
1897
1898 def get_user_limiter(user_id):
1899 try:
1900 return USER_LIMITERS[user_id]
1901 except KeyError:
1902 per_user_limiter = trio.CapacityLimiter(MAX_THREADS_PER_USER)
1903 global_limiter = trio.current_default_thread_limiter()
1904 # IMPORTANT: acquire the per_user_limiter before the global_limiter.
1905 # If we get 100 jobs for a user at the same time, we want
1906 # to only allow 3 of them at a time to even compete for the
1907 # global thread slots.
1908 combined_limiter = CombinedLimiter(per_user_limiter, global_limiter)
1909 USER_LIMITERS[user_id] = combined_limiter
1910 return combined_limiter
1911
1912
1913 async def run_sync_in_thread_for_user(user_id, sync_fn, *args):
1914 combined_limiter = get_user_limiter(user_id)
1915 return await trio.to_thread.run_sync(sync_fn, *args, limiter=combined_limiter)
1916
1917
1918 .. module:: trio.to_thread
1919 .. currentmodule:: trio
1920
1921 Putting blocking I/O into worker threads
1922 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1923
1924 .. autofunction:: trio.to_thread.run_sync
1925
1926 .. autofunction:: trio.to_thread.current_default_thread_limiter
1927
1928
1929 .. module:: trio.from_thread
1930 .. currentmodule:: trio
1931
1932 Getting back into the Trio thread from another thread
1933 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1934
1935 .. autofunction:: trio.from_thread.run
1936
1937 .. autofunction:: trio.from_thread.run_sync
1938
1939
1940 This will probably be clearer with an example. Here we demonstrate how
1941 to spawn a child thread, and then use a :ref:`memory channel
1942 <channels>` to send messages between the thread and a Trio task:
1943
1944 .. literalinclude:: reference-core/from-thread-example.py
1945
1946 .. note::
1947
1948 The ``from_thread.run*`` functions reuse the host task that called
1949 :func:`trio.to_thread.run_sync` to run your provided function, as long as you're
1950 using the default ``abandon_on_cancel=False`` so Trio can be sure that the task will remain
1951 around to perform the work. If you pass ``abandon_on_cancel=True`` at the outset, or if
1952 you provide a :class:`~trio.lowlevel.TrioToken` when calling back in to Trio, your
1953 functions will be executed in a new system task. Therefore, the
1954 :func:`~trio.lowlevel.current_task`, :func:`current_effective_deadline`, or other
1955 task-tree specific values may differ depending on keyword argument values.
1956
1957 You can also use :func:`trio.from_thread.check_cancelled` to check for cancellation from
1958 a thread that was spawned by :func:`trio.to_thread.run_sync`. If the call to
1959 :func:`~trio.to_thread.run_sync` was cancelled, then
1960 :func:`~trio.from_thread.check_cancelled` will raise :func:`trio.Cancelled`.
1961 It's like ``trio.from_thread.run(trio.sleep, 0)``, but much faster.
1962
1963 .. autofunction:: trio.from_thread.check_cancelled
1964
1965 Threads and task-local storage
1966 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1967
1968 When working with threads, you can use the same `contextvars` we discussed above,
1969 because their values are preserved.
1970
1971 This is done by automatically copying the `contextvars` context when you use any of:
1972
1973 * `trio.to_thread.run_sync`
1974 * `trio.from_thread.run`
1975 * `trio.from_thread.run_sync`
1976
1977 That means that the values of the context variables are accessible even in worker
1978 threads, or when sending a function to be run in the main/parent Trio thread using
1979 `trio.from_thread.run` *from* one of these worker threads.
1980
1981 But it also means that as the context is not the same but a copy, if you `set` the
1982 context variable value *inside* one of these functions that work in threads, the
1983 new value will only be available in that context (that was copied). So, the new value
1984 will be available for that function and other internal/children tasks, but the value
1985 won't be available in the parent thread.
1986
1987 If you need to modify values that would live in the context variables and you need to
1988 make those modifications from the child threads, you can instead set a mutable object
1989 (e.g. a dictionary) in the context variable of the top level/parent Trio thread.
1990 Then in the children, instead of setting the context variable, you can ``get`` the same
1991 object, and modify its values. That way you keep the same object in the context
1992 variable and only mutate it in child threads.
1993
1994 This way, you can modify the object content in child threads and still access the
1995 new content in the parent thread.
1996
1997 Here's an example:
1998
1999 .. literalinclude:: reference-core/thread-contextvars-example.py
2000
2001 Running that script will result in the output:
2002
2003 .. code-block:: none
2004
2005 Processed user 2 with message Hello 2 in a thread worker
2006 Processed user 0 with message Hello 0 in a thread worker
2007 Processed user 1 with message Hello 1 in a thread worker
2008 New contextvar value from worker thread for user 2: Hello 2
2009 New contextvar value from worker thread for user 1: Hello 1
2010 New contextvar value from worker thread for user 0: Hello 0
2011
2012 If you are using ``contextvars`` or you are using a library that uses them, now you
2013 know how they interact when working with threads in Trio.
2014
2015 But have in mind that in many cases it might be a lot simpler to *not* use context
2016 variables in your own code and instead pass values in arguments, as it might be more
2017 explicit and might be easier to reason about.
2018
2019 .. note::
2020
2021 The context is automatically copied instead of using the same parent context because
2022 a single context can't be used in more than one thread, it's not supported by
2023 ``contextvars``.
2024
2025
2026 .. _interactive debugging:
2027
2028
2029 Interactive debugging
2030 ---------------------
2031
2032 When you start an interactive Python session to debug any async program
2033 (whether it's based on ``asyncio``, Trio, or something else), every await
2034 expression needs to be inside an async function:
2035
2036 .. code-block:: console
2037
2038 $ python
2039 Python 3.10.6
2040 Type "help", "copyright", "credits" or "license" for more information.
2041 >>> import trio
2042 >>> await trio.sleep(1)
2043 File "<stdin>", line 1
2044 SyntaxError: 'await' outside function
2045 >>> async def main():
2046 ... print("hello...")
2047 ... await trio.sleep(1)
2048 ... print("world!")
2049 ...
2050 >>> trio.run(main)
2051 hello...
2052 world!
2053
2054 This can make it difficult to iterate quickly since you have to redefine the
2055 whole function body whenever you make a tweak.
2056
2057 Trio provides a modified interactive console that lets you ``await`` at the top
2058 level. You can access this console by running ``python -m trio``:
2059
2060 .. code-block:: console
2061
2062 $ python -m trio
2063 Trio 0.21.0+dev, Python 3.10.6
2064 Use "await" directly instead of "trio.run()".
2065 Type "help", "copyright", "credits" or "license" for more information.
2066 >>> import trio
2067 >>> print("hello..."); await trio.sleep(1); print("world!")
2068 hello...
2069 world!
2070
2071 If you are an IPython user, you can use IPython's `autoawait
2072 <https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-autoawait>`__
2073 function. This can be enabled within the IPython shell by running the magic command
2074 ``%autoawait trio``. To have ``autoawait`` enabled whenever Trio installed, you can
2075 add the following to your IPython startup files.
2076 (e.g. ``~/.ipython/profile_default/startup/10-async.py``)
2077
2078 .. code-block::
2079
2080 try:
2081 import trio
2082 get_ipython().run_line_magic("autoawait", "trio")
2083 except ImportError:
2084 pass
2085
2086 Exceptions and warnings
2087 -----------------------
2088
2089 .. autoexception:: Cancelled
2090
2091 .. autoexception:: TooSlowError
2092
2093 .. autoexception:: WouldBlock
2094
2095 .. autoexception:: EndOfChannel
2096
2097 .. autoexception:: BusyResourceError
2098
2099 .. autoexception:: ClosedResourceError
2100
2101 .. autoexception:: BrokenResourceError
2102
2103 .. autoexception:: RunFinishedError
2104
2105 .. autoexception:: TrioInternalError
2106
2107 .. autoexception:: TrioDeprecationWarning
2108 :show-inheritance: