Asyncio, tasks and cancellation
Write cooperative I/O flows with bounded lifetimes.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain async is cooperative concurrency
- Apply own child tasks
- Reason about bridge blocking work carefully
Async is cooperative concurrency
Async code cooperates on one event loop. An async function produces a coroutine when called; awaiting a pending operation lets other ready work progress. Merely adding async does not move computation to another core.
Understand first
A service waiting for independent I/O can let other requests progress instead of blocking one execution path per wait. Know functions and return values first. This example needs Python 3.11+ asyncio support but no network or real OS thread creation.
Words you will see
- Coroutine
- A resumable async computation, represented by an object when an async function is called.
- Event loop
- The scheduler that runs ready callbacks and async tasks.
- await
- An expression that waits for an awaitable result and can suspend the current coroutine.
Creation is not completion
Calling label creates pending; it does not yet execute the body to produce QUEUE. main prints created first, then awaits that specific coroutine. label yields with sleep(0), resumes and returns the uppercased string. The second print happens only after that result is available.
asyncio.run creates and closes the loop for this standalone script. In a host that already owns a running loop, the host must integrate execution appropriately; do not nest asyncio.run in that loop. A browser runtime's adapter, not this lesson, owns that integration.
Yield useful work, not wishful concurrency
An await of an already ready result need not suspend. A long synchronous CPU loop or blocking socket call inside async def can occupy the loop and stop other tasks. Use an actual async I/O API or move suitable blocking I/O off the loop deliberately.
This fixture has one coroutine and no real I/O. It teaches lifetime and syntax, not throughput or a guaranteed task interleaving. For one tiny computation, an ordinary function is simpler. Never leave an unawaited coroutine as a claimed successful background job.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
pending = label('queue')Create a coroutine object without obtaining its result yet.
print('created')Run an ordinary statement before awaiting.
result = await pendingOwn and await this coroutine to completion.
print(result)Display the returned QUEUE, not the coroutine object's representation.
async def creates a coroutine function; calling it does not immediately run it to completion. await lets other ready tasks progress while the awaited operation is pending. A blocking CPU loop or synchronous socket/file call can still block the event-loop thread.
Conceptual cooperative scheduling, not a measured runtime trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- RunA coroutine executes ordinary statements on the loop thread.
- WaitA pending await lets the loop run other ready work.
- ResumeWhen its awaited operation completes, the coroutine becomes eligible to continue.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Use a different input.
Try: Change label('queue') to label('cache').
The second line becomes CACHE; creation still prints first.
Report completion explicitly.
Try: Add print('finished') after print(result).
finished comes after QUEUE because the await has completed before both prints.
Before you move on
If label('cache') is called but never awaited or scheduled, may its returned CACHE be treated as a completed result?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The call produced a coroutine object, not the string result. It needs one owned execution path and observed completion.
Own child tasks
A task schedules a coroutine, and a task group gives related tasks one owner. The group waits for its children and coordinates failure; this is safer than forgetting background tasks and their errors.
Understand first
If two requests belong to one operation, the caller should not return while one child still runs unnoticed. Know coroutines, try/finally and exceptions before this Python 3.11+ TaskGroup fixture. The shared set is local fixture state on one loop, not a cross-thread coordination tool.
Words you will see
- Task
- A scheduled coroutine with a lifetime and observable result or exception.
- TaskGroup
- A scope that owns child tasks and waits for them when leaving.
- Exception group
- A structure containing failures from related work, handled by except* clauses.
The scope owns both success and failure
Both children are created before main leaves the TaskGroup body. Each child first yields. The first raises ValueError; the group coordinates any sibling cancellation and waits for child termination. The second might already have finished, so the program does not assume it was cancelled.
Every child that starts work reaches finally on success, error or cancellation. The sorted cleaned set records names without exposing order. except* ValueError handles the expected failure group, then main reports cleanup only after the group has finished.
Do not detach by accident
The group does not make work transactional: a completed external side effect is not rolled back when a sibling fails. Decide whether partial side effects need compensation or idempotency. Collect results only after successful group exit when the operation requires all children.
A deliberately detached task needs a retained handle, failure reporting and a shutdown owner. Prefer a task group for bounded related work. With an empty group, there is nothing to await; that is not evidence that an external operation succeeded. This fixture uses no external services.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
await asyncio.sleep(0)Give each started child a cooperative suspension point.
raise ValueError(name)Make first fail visibly rather than return a normal result.
cleaned.add(name)Record bounded cleanup in finally.
print(sorted(cleaned))Report the completed cleanup set after group exit, not a scheduler ordering.
Use TaskGroup on Python 3.11+ when tasks belong to one scope. Handle expected exceptions at an appropriate boundary and let cancellation propagate after cleanup. Detached fire-and-forget tasks need explicit lifetime, error reporting and shutdown policies.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Make both children succeed.
Try: Change work('first', True) to work('first').
The failure message disappears; both names remain in the cleanup list.
Name the second child differently.
Try: Change 'second' to 'backup' in its creation call.
The cleanup list becomes ['backup', 'first']; sorting is reporting policy, not task order.
Before you move on
If the second child already returned before the first failed, must TaskGroup undo its work?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The group owns lifetimes and propagates errors, not transactional rollback. External side effects require their own recovery contract.
Collect scoped task results
A successful task group makes its results safe to inspect after the scope exits. Choosing output order after completion avoids depending on which child the scheduler ran first.
Understand first
This preserved original program demonstrates successful ownership without network or clock dependencies. It requires Python 3.11+ asyncio and TaskGroup support. Browser event-loop integration must be provided by the shared runtime; this sample is not a threads-or-processes test.
Words you will see
- Result handle
- A retained task object used to observe completion or failure.
- Successful scope exit
- Leaving the task group after all children finish without an unhandled group failure.
- Presentation order
- The order a caller deliberately uses when displaying results.
Wait first, inspect second
main stores both returned task handles. The async with block does not finish successfully until the group has finished its children. first.result() and second.result() are therefore read afterwards, when their values are available.
print receives the first task's value before the second's. That fixes API WORKER even if worker internally finishes first. Moving prints into label would instead report execution events and would require an explicitly non-authoritative scheduling explanation.
Observe failure rather than copying expected output
Calling result on an unfinished task raises InvalidStateError; on a failed task it raises that task's exception. If a child failed in this group, group exit would fail before the final print. Do not display API WORKER as a substitute for that exception.
For two independent tiny labels, sequential awaits would also work and may be simpler. A task group matters when owned operations can overlap useful waits. sleep(0) is a deterministic yielding tool here, not measured network latency or proof of faster execution.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
async with asyncio.TaskGroup() as group:Open the children's owning scope.
first = group.create_task(label('api'))Retain the task that will return API.
second = group.create_task(label('worker'))Retain the second independent result handle.
print(first.result(), second.result())Choose output order after both children are complete.
The group waits for its children. Output order is chosen after completion rather than relying on task scheduling order.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reverse presentation order.
Try: Swap the two result calls in print.
The output becomes WORKER API without changing task creation.
Try empty text in one task.
Try: Change label('api') to label('').
The first value is empty; print still separates the two arguments with one space.
Before you move on
If the two print arguments are swapped, must task creation order also change?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Printing second.result() before first.result() after successful group exit yields WORKER API regardless of creation or completion order.
Where this idea earns its place
Asyncio coordinates cooperative concurrency, usually around I/O that can yield control. It does not turn every operation inside async def into nonblocking work. The event loop is a shared execution resource, so one blocking call can delay unrelated requests even when their own code appears properly asynchronous.
Follow the mechanism step by step
Calling an async function creates a coroutine. Awaiting or scheduling it drives execution until a suspension point. TaskGroup scopes related tasks and waits for their completion or failure handling. A task's lifetime and ownership should be explicit; merely creating it does not define who reports its errors or cancels it at shutdown.
Work through a concrete application
Trace two label tasks that yield once and return results, then print results only after their group exits. Next replace the yielded operation with a blocking call to understand loop stalls. Use an async adapter or bounded thread offload for appropriate blocking I/O, and keep a total timeout around the logical operation.
Failure cases and misleading shortcuts
Swallowing cancellation can prevent shutdown or leave resources active. A timeout can stop the caller waiting without guaranteeing an underlying thread or remote side effect stopped. Unbounded task creation can also retain an enormous amount of pending work even when a semaphore limits active calls.
Cost, ownership and alternatives
Model active concurrency, pending queue size, external rate limits and connection pools separately. CPU-heavy Python work may need a process/native implementation rather than additional async tasks. Cancellation cleanup must be bounded and preserve important failure context rather than replacing it with a success-shaped empty result.
Verify the contract
Test normal completion, one child failure, cancellation during a known operation and cleanup after timeout. Coordinate test points with events rather than sleep-based guesses. Observe loop lag in integration tests with the real adapters, because a pure coroutine fixture cannot prove a third-party library yields appropriately.
Transfer question: If a request times out while asyncio.to_thread is running, is the thread guaranteed to stop?
No. The coroutine's wait and the underlying thread execution have different lifetimes. Configure the blocking operation's own timeout, bound offload concurrency and design cooperative cancellation or reconciliation where needed. Do not report that a remote side effect was cancelled solely because the await ended.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Collect scoped task results
Without copying the worked code, reproduce its observable contract: The group waits for its children. Output order is chosen after completion rather than relying on task scheduling order. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: model terminal cancellation states
Implement settle_events(events), a deterministic lifecycle reducer. A completed or cancelled task must never be revived by later events.
The contract
- events is a finite list of (name, action) string tuples. action is exactly 'start', 'finish' or 'cancel'; other types/actions are outside this exercise's domain.
- Return a fresh exact dict. start creates a previously unseen name with 'running'. Further starts are ignored. finish/cancel changes only an existing running task to 'done'/'cancelled'.
- Ignore finish/cancel for unseen or terminal names. Terminal names never restart. Preserve the insertion order of first starts, and do not mutate events.
- Empty events returns {}. This is a declared state machine, not asyncio's full task implementation or evidence that cancellation was delivered to real I/O.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- normal completion
out = settle_events([('a', 'start'), ('a', 'finish')]) assert type(out) is dict and out == {'a': 'done'} - empty state ownership
a = settle_events([]) b = settle_events([]) assert type(a) is dict and a == {} and b == {} and a is not b - cancel is terminal
out = settle_events([('a', 'start'), ('a', 'cancel'), ('a', 'finish'), ('a', 'start')]) assert type(out) is dict and out == {'a': 'cancelled'} - unseen terminal events are ignored
out = settle_events([('x', 'cancel'), ('y', 'finish'), ('z', 'start')]) assert type(out) is dict and out == {'z': 'running'} - duplicates do not revive done tasks
out = settle_events([('a', 'start'), ('a', 'start'), ('a', 'finish'), ('a', 'cancel'), ('a', 'finish')]) assert type(out) is dict and out == {'a': 'done'} - insertion order and input ownership
events = [('b', 'start'), ('a', 'start'), ('b', 'cancel')] out = settle_events(events) assert type(out) is dict and out == {'b': 'cancelled', 'a': 'running'} and list(out) == ['b', 'a'] assert events == [('b', 'start'), ('a', 'start'), ('b', 'cancel')] out['a'] = 'edited' assert settle_events(events) == {'b': 'cancelled', 'a': 'running'}
Why is this reducer not a real cancellation test?
It applies declared string transitions; it never schedules a coroutine, interrupts I/O or observes cleanup. With n events and u started names it takes O(n) expected time and O(u) result space under ordinary dictionary lookup assumptions.
Guided: release owned handles in reverse order
Implement cleanup_plan(acquired). Build a reverse-order cleanup plan that keeps every successful acquisition, even repeated labels.
The contract
- acquired is a finite list of string labels, one entry per successful acquisition. Labels need not be unique; two equal labels still represent two separate owned handles.
- Return an exact tuple of the labels in reverse acquisition order. Empty input returns (). Do not sort, deduplicate or mutate acquired.
- Only successful acquisitions are in the input; unacquired resources must not be added. Strings are immutable, so the tuple can safely contain their references.
- This is a plan for a finally block, not actual resource release or evidence that async cancellation is complete. A real release action needs bounded, failure-aware cleanup.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- nested ownership unwinds inside out
out = cleanup_plan(['connection', 'transaction', 'cursor']) assert type(out) is tuple and out == ('cursor', 'transaction', 'connection') - no acquisitions
out = cleanup_plan([]) assert type(out) is tuple and out == ()
- one acquisition
out = cleanup_plan(['socket']) assert type(out) is tuple and out == ('socket',) - repeated labels are separate handles
out = cleanup_plan(['file', 'file', 'lock']) assert type(out) is tuple and out == ('lock', 'file', 'file') - order is not alphabetical
out = cleanup_plan(['a', 'z', 'm', '']) assert type(out) is tuple and out == ('', 'm', 'z', 'a') - input preserved across repeated planning
acquired = ['outer', 'inner'] first = cleanup_plan(acquired) second = cleanup_plan(acquired) assert type(first) is tuple and first == ('inner', 'outer') and second == first and acquired == ['outer', 'inner']
What must happen after building this tuple before cleanup can be claimed complete?
The owner must actually invoke and observe the bounded release operations, handling failures without hiding cancellation. This plan takes O(n) time and O(n) result space for n acquired entries; it does not execute any release.
Transfer: collect only results within a deadline
Implement deadline_results(records, deadline). The changed requirement is a clock-bound publication rule, not just a terminal task state.
The contract
- records is a finite list of (name, completed_at, value) tuples: name is a string; completed_at is a nonnegative exact integer tick; value is an exact integer. Input is an observation list, not necessarily sorted.
- deadline is an exact integer. Raise ValueError when it is negative, even for empty records. Keep results with completed_at <= deadline, including equality.
- Return a fresh exact list of exact (name, value) tuples in observation order. Preserve repeated names and repeated results. Do not sort or mutate records.
- Empty valid input returns []. Ticks use one controlled clock. This non-authoritative simulation neither cancels late tasks nor proves external work stopped; actual async deadlines require the local/runtime cancellation contract.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- filter without reordering observations
out = deadline_results([('late', 7, 9), ('early', 2, 4), ('edge', 5, 6)], 5) assert type(out) is list and out == [('early', 4), ('edge', 6)] and all(type(pair) is tuple for pair in out) - empty result ownership
a = deadline_results([], 0) b = deadline_results([], 0) assert type(a) is list and a == [] and b == [] and a is not b
- exact boundary is timely
out = deadline_results([('a', 0, 1), ('b', 1, 2)], 0) assert type(out) is list and out == [('a', 1)] and type(out[0]) is tuple - all late is not an error
out = deadline_results([('a', 3, 5), ('b', 9, 8)], 2) assert type(out) is list and out == [] - duplicate names preserve individual results
out = deadline_results([('same', 4, 7), ('same', 1, 7), ('other', 2, -1)], 4) assert type(out) is list and out == [('same', 7), ('same', 7), ('other', -1)] - invalid deadline and source preservation
raised = False try: deadline_results([], -1) except ValueError: raised = True assert raised records = [('b', 4, 2), ('a', 1, 3)] out = deadline_results(records, 4) assert type(out) is list and out == [('b', 2), ('a', 3)] and out is not records and records == [('b', 4, 2), ('a', 1, 3)]
What additional duty does a real caller have for results excluded by the deadline?
It must own the late work's cancellation, cleanup or explicit continuation policy; filtering a list stops nothing. The filter uses O(n) time and O(k) result space for n observations and k accepted results.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneDeadlines and cleanup
Cancellation asks async work to stop at a cooperative boundary. A deadline limits waiting, while finally gives owned resources a cleanup path. Cleanup must finish in bounded time and cancellation should normally propagate.
Understand first
A request may lose its caller or exceed its allowed lifetime while holding a resource. Understand task ownership and finally before adding deadlines. This fixture coordinates using an event rather than guessing how many milliseconds let a task start.
Words you will see
- Deadline
- A latest allowed completion time, normally based on a monotonic clock.
- CancelledError
- The async cancellation exception that normally propagates after cleanup.
- Cleanup
- Releasing resources or restoring owned state when leaving an operation.
Make cancellation observable and bounded
worker records acquisition and signals ready before awaiting an event that never becomes set. main waits for ready, so it knows the cleanup region has been entered before cancel. Awaiting task then observes its termination rather than abandoning its handle.
finally appends release before CancelledError reaches the awaiting owner. main catches cancellation only at this deliberate owner boundary and records it. No arbitrary sleep or elapsed-time assertion decides success; the script has an explicit causal chain.
Timeouts still need a resource policy
In Python 3.11+, asyncio.timeout wraps a bounded await region and converts its own cancellation into TimeoutError outside the context. wait_for also has cancellation semantics that must be understood for the supported runtime. A timeout is not proof that external work or a thread was forcibly stopped.
Use short, reliable cleanup and let unexpected cancellation propagate. Awaiting unbounded work in finally can delay shutdown indefinitely. Shielding work needs a separate lifetime owner, not a way to forget it. In a local lab, test cancellation at explicit events rather than asserting millisecond precision.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
ready.set()Signal that worker has entered the resource-owning region.
await ready.wait()Wait for that known state instead of sleeping.
task.cancel()Request cooperative cancellation of the owned task.
events.append('release')Run finally before the awaiting owner records cancellation.
Use asyncio.timeout or wait_for according to the supported runtime and cancellation contract. Catching BaseException or swallowing CancelledError can prevent shutdown. Keep finally blocks bounded and understand whether a timeout cancels underlying work or merely stops waiting.
Conceptual cancellation lifecycle, not a wall-clock measurement
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- RunningThe operation owns a resource and may be suspended at await.
- Cancel requestedA cancellation exception is delivered at a suitable cooperative point.
- Cleanupfinally releases owned resources; the cancellation or timeout remains observable.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Record the owner's request.
Try: Add events.append('request') immediately before task.cancel().
The sequence becomes acquire, request, release, cancelled.
Rename the acquired resource event.
Try: Replace 'acquire' with 'open'.
Only the first label changes; the handshake still guarantees cleanup was entered.
Before you move on
Why is await task needed after task.cancel() in this fixture?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
cancel requests a transition; awaiting observes completion, including cleanup and the cancellation exception. Dropping the handle would not verify release.
Bridge blocking work carefully
Moving blocking I/O off the event loop is a bridge, not an unlimited worker policy. Bound outstanding jobs before dispatching them, and do not claim that to_thread makes CPU-heavy Python parallel under a conventional GIL.
Understand first
Starting one task per record can exhaust memory even if each call eventually waits. This fixture teaches a dispatch bound using list slices. A real blocking-I/O lab needs a supported local CPython thread environment; browser WebAssembly must not pretend it ran to_thread.
Words you will see
- Blocking operation
- A call that occupies its executing thread while waiting or computing.
- to_thread
- An asyncio helper for running a synchronous callable in a thread without blocking the loop on the call itself.
- Outstanding work
- All admitted work that has not finished, including running and waiting jobs.
Limit admission before creating all tasks
The planner divides five job names into waves of two, two and one. A dispatcher following this policy would finish one wave before starting the next. The model stores only names and performs no I/O, so its maximum is a policy size, not a measured active-thread count.
A semaphore inside a million already-created tasks bounds entry but not the million task objects. A bounded worker queue or incremental dispatch can cap admitted work as well as active calls. Waved execution is simpler but can leave capacity idle while one slow job finishes.
Respect the bridge's limits
Use an async client when it fits the external API. Use to_thread for suitable blocking I/O when thread safety, client ownership and shutdown are understood. Cancelling its awaiting coroutine does not forcibly kill arbitrary synchronous code already running in a thread.
For CPU-heavy Python, consider processes or algorithm changes after measuring the real runtime. Validate limit > 0 in a reusable planner; an empty job list has maximum zero. This deterministic fixture verifies grouping and preservation only, not thread behavior, latency or I/O success.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
limit = 2Set a positive dispatch capacity.
for start in range(0, len(jobs), limit):Visit consecutive starts zero, two and four.
waves.append(jobs[start:start + limit])Copy one bounded group without deleting original jobs.
print(max(map(len, waves), default=0))Report the largest planned wave, including a safe empty default.
asyncio.to_thread can move suitable blocking I/O off the loop, but does not make CPU-heavy Python work scale under a conventional GIL. Limit concurrency and reuse clients safely. Never start one unbounded task per record in a million-row input.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Set a one-job bound.
Try: Change limit = 2 to limit = 1.
There are five singleton waves and the reported maximum is one.
Test absent jobs.
Try: Set jobs = [].
waves is [] and the maximum is zero; default avoids an empty-max error.
Before you move on
If each wave has at most three jobs, does that prove the original input stream was bounded?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. A planner that first stores the entire stream can still use unbounded input memory. Admission, storage and active concurrency are separate bounds.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.