python / python/cpython

TaskGroup: tg.cancel() shouldn't block create_task() allow cooperative cancellation

未关闭
#150,355 6 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib topic-asyncio type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Currently, when a TaskGroup is explicitly cancelled via tg.cancel(), any subsequent call to tg.create_task() raises:

RuntimeError: TaskGroup <TaskGroup cancelling> is shutting down

This contradicts the TODO in the test test_taskgroup_cancel_before_create_task, which states:

This behavior is not ideal. We'd rather have no exception raised, and the child task run until the first await.

Proposed change:
After an explicit tg.cancel() (not after a failure-induced abort), create_task() should succeed. The new task should run its synchronous code up to the first await, then receive CancelledError

For failure-driven aborts (e.g., an exception in another task), the existing RuntimeError is preserved to prevent unsafe task creation during error cleanup.

A PR implementing this change (with a new _explicitly_cancelled flag) is ready and passes all existing tests.

This resolves the TODO and makes TaskGroup behavior more intuitive when voluntarily cancelled.

Linked PRs
  • gh-150357

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 test_taskgroup_cancel_before_create_task TODO 以及 issue 中描述的 TaskGroup cancel/create_task 入口开始。比较显式的 tg.cancel() 与由失败驱动的中止行为。完成标准是:显式取消后创建的任务在接收 CancelledError 之前会执行其同步代码,而由失败驱动的中止仍会引发 RuntimeError。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
功能
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。