Async Techniques and Examples in Python Transcripts
Chapter: Built on asyncio
Lecture: Demo: Cancellation with Trio

Login or purchase this course to watch this video and the rest of the course contents.
0:00 So we converted from asyncio to Trio
0:03 and we saw things got simpler this async with block.
0:06 The nursery concept is quite simple.
0:08 Let me show you how we can use that
0:10 for even greater benefit.
0:11 I talked about cancellation. Now watch this.
0:14 Let's suppose we want this to run for either
0:17 five seconds and finish successfully
0:19 or if it goes past five seconds
0:20 we're going to cancel all the work.
0:22 OK, even all the child tasks that maybe
0:24 those processes themselves kicked off.
0:27 How'd we do that? It sounds complicated, right?
0:30 Watch this. With trio.move_on_after, let's say 5.
0:36 How about that? Let's see what happens here.
0:39 It should run for a little bit.
0:40 Do some generating, do some producing, some consuming
0:43 and then it should cancel.
0:45 So this line should print out in just about five seconds.
0:48 Let's find out what happens, it's working, and it's working.
0:52 Five seconds are past, and boom. We ran out of time. We're done.
0:57 We canceled them, straight away. How cool is that?
1:01 So if we make that less work, two, two, and four
1:04 something like that, should be able to produce
1:06 all the work and just finish early.
1:08 No cancellation, 2.42 seconds.
1:11 But if it takes too long, this cancellation
1:13 kicks in and off it goes.
1:15 So these interesting coordination concepts
1:18 like to have this block only run for so long
1:21 with some sort of time out, also if this thing kicks off
1:25 child tasks and then you decide to cancel it or time it out
1:29 or something like that or this one has an error.
1:32 Even those get canceled if they're still running.
1:34 There's really interesting stuff that happens
1:36 around this behind the scenes that does happen
1:39 in normal asyncio, definitely doesn't happen
1:41 in threading or multiprocessing that makes this
1:44 a really nice coordination framework.
1:46 And that's Trio, like I said
1:47 there's actually a lot more to it.
1:49 You can build really interesting things from the ground up.
1:51 But I think this is enough to give you
1:53 some inspiration and some ideas to go explore it
1:55 if it's useful for you.