Skip to content

[kernel] Prevent duplicate defunct enqueue for deleted threads. - #11519

Open
Rbb666 wants to merge 1 commit into
RT-Thread:masterfrom
Rbb666:defunct
Open

Rbb666 wants to merge 1 commit into
RT-Thread:masterfrom
Rbb666:defunct

Conversation

@Rbb666

@Rbb666 Rbb666 commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

拉取/合并请求描述:(PR description)

为什么提交这份 PR (why to submit this PR)

线程自然退出、显式删除或分离后,在对象仍有效但尚未完成回收时再次调用 rt_thread_delete() / rt_thread_detach(),可能将同一线程重复加入 defunct 队列,造成链表破坏或重复清理。本 PR 为清理过程增加一次性保护。

Prevent duplicate defunct enqueue and cleanup while the thread object is still valid.

你的解决方案是什么 (what is your solution)

  • 在 struct rt_thread 中增加独立的 rt_uint8_t defunct 字段,由公共初始化路径 _thread_init() 清零,覆盖动态创建、静态初始化及合法的重新初始化。
  • _thread_mark_defunct() 在 thread->spinlock 下完成检查和置位。标志表示“已取得清理权”,在 mutex 清理和入队之前设置,一次生命周期内不再清零。
  • 标志使用独立字节,与调度器位域分离,避免不同锁保护下对共享位域存储进行读改写时相互覆盖。注释说明了保护规则和生命周期。
  • 保持 close → mark → mutex 清理 → defunct 入队的顺序。线程锁仅保护检查和置位;成功取得清理权的路径执行一次清理和入队,后续重复 delete/detach 返回 -RT_ERROR。
  • 保护要求线程对象仍有效,不保证已释放句柄的安全,也不扩展为解决运行中线程的跨核提前回收问题。

Use a separate byte in the thread object, protected by the thread spinlock, to claim cleanup once per lifetime. This avoids sharing storage with scheduler bit-fields that use different locking.

修改文件 / Changed files

  • include/rtdef.h:增加独立的线程清理标志。
  • src/thread.c:初始化标志,并在退出、删除和分离路径中保护一次性清理。
  • src/utest/thread_tc.c:补充重复操作、静态对象复用和双核并发删除回归测试。

测试覆盖 / Regression coverage

  • 动态线程自然退出后,在 cleanup 中再次 delete,验证返回 -RT_ERROR 且只清理一次。
  • 动态线程显式删除后,在 cleanup 中再次 delete,验证相同的负返回与清理次数。
  • 单核、非 SMART 配置下,验证静态线程重复 detach、重新初始化同一 TCB 后自然退出再 detach;通过后续 cleanup 确认旧生命周期已完成回收。
  • SMP 至少两核时,两个 worker 分别绑定 CPU 0/1,并发删除同一个未启动的动态线程。目标 cleanup 保持对象存活,直到在途删除完成;验证一次 RT_EOK、一次 -RT_ERROR 和一次 cleanup。
  • 测试增加有界等待与超时状态保护。内核调用本身永久卡死仍需外部 watchdog 判失败。

请提供验证的 BSP 和 config (provide the config and BSP)

  • BSP:bsp/qemu-vexpress-a9,分别使用 UP(1 核)和 SMP(2 核)配置,均未启用 SMART。
  • 工具:Arm GNU Toolchain 13.3.1、SCons 4.10.1、QEMU ARM 8.0.94。
  • 验证日期:2026-10-17。
  • 在临时 BSP 副本中从 .config 生成 rtconfig.h,仓库 BSP 配置未改动。

两种配置均在默认 BSP 配置上启用:

CONFIG_RT_USING_UTESTCASES=y
CONFIG_RT_UTEST_THREAD=y
CONFIG_UTEST_THR_STACK_SIZE=8192

SMP 配置额外启用:

CONFIG_RT_USING_SMP=y
CONFIG_RT_CPUS_NR=2
CONFIG_SYSTEM_THREAD_STACK_SIZE=4096

构建与运行命令:

python -m SCons --pyconfig-silent
python -m SCons -j8 --strict
utest_run -thread core.thread_tc

QEMU 使用 -M vexpress-a9,UP 为 -smp 1,SMP 为 -smp 2。

配置 严格编译 core.thread_tc
Cortex-A9 UP / 1 核 通过 通过,运行 1 次
Cortex-A9 SMP / 2 核 通过 通过,运行 1 次

两次运行均输出:

[  PASSED  ] [ result   ] testcase (core.thread_tc)
[==========] [ utest    ] finished

git diff --check 通过。在上述配置中,sizeof(struct rt_thread) 分别由 UP 的 168 增至 172 字节、SMP 的 176 增至 180 字节;需重编依赖线程结构体布局的代码。

验证范围 / Validation limits

上述结果是本地严格构建及 QEMU 单次回归结果,不代表全部 utest 或压力测试通过。AArch64 / ARCH_USING_HW_THREAD_SELF 的运行路径尚未实测;SMP 新增用例的目标未启动,不宣称覆盖运行中线程自然退出与远端删除的专项竞态。

Both local UP and SMP strict builds and core.thread_tc runs passed. AArch64 runtime behavior and the running-thread exit-versus-delete race were not tested.

  • action:本地验证结果如上;本次推送后的 GitHub Actions 结果以 PR Checks 为准。

当前拉取/合并请求的状态 Intent for your PR

必须选择一项 Choose one (Mandatory):

  • 本拉取/合并请求是一个草稿版本 This PR is for a code-review and is intended to get feedback
  • 本拉取/合并请求是一个成熟版本 This PR is mature, and ready to be integrated into the repo

代码质量 Code Quality:

我在这个拉取/合并请求中已经考虑了 As part of this pull request, I've considered the following:

  • 已经仔细查看过代码改动的对比 Already check the difference between PR and old code
  • 代码风格正确,包括缩进空格,命名及其他风格 Style guide is adhered to, including spacing, naming and other styles
  • 没有垃圾代码,代码尽量精简,不包含#if 0代码,不包含已经被注释了的代码 All redundant code is removed and cleaned up
  • 所有变更均有原因及合理的,并且不会影响到其他软件组件代码或BSP All modifications are justified and not affect other components or BSP
  • 对难懂代码均提供对应的注释 I've commented appropriately where code is tricky
  • 代码是高质量的 Code in this PR is of high quality
  • 已经使用formatting 等源码格式化工具确保格式符合RT-Thread代码规范 This PR complies with RT-Thread code specification
  • 如果是新增bsp, 已经添加ci检查到.github/ALL_BSP_COMPILE.json 详细请参考链接BSP自查

@github-actions

github-actions Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

👋 感谢您对 RT-Thread 的贡献!Thank you for your contribution to RT-Thread!

为确保代码符合 RT-Thread 的编码规范,请在你的仓库中执行以下步骤运行代码格式化工作流(如果格式化CI运行失败)。
To ensure your code complies with RT-Thread's coding style, please run the code formatting workflow by following the steps below (If the formatting of CI fails to run).


🛠 操作步骤 | Steps

  1. 前往 Actions 页面 | Go to the Actions page
    点击进入工作流 → | Click to open workflow →

  2. 点击 Run workflow | Click Run workflow

  • Use workflow from 保持默认分支(通常为 master)
    Keep the default branch (usually master) in Use workflow from
  • 在 branch 输入框填写 PR 分支 defunct
    Enter PR branch defunct in the branch field
  • 设置需排除的文件/目录(目录请以"/"结尾)
    Set files/directories to exclude (directories should end with "/")
  1. 等待工作流完成 | Wait for the workflow to complete
    格式化后的代码将作为独立提交推送至你的分支。
    The formatting changes will be pushed to your branch as a separate commit.

完成后,提交将自动更新至 defunct 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the defunct branch automatically, and the related Pull Request will be updated.

如有问题欢迎联系我们,再次感谢您的贡献!💐
If you have any questions, feel free to reach out. Thanks again for your contribution!

@github-actions

github-actions Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

📌 Code Review Assignment

🏷️ Tag: kernel

Reviewers: @GorrayLi @ReviewSun @hamburger-os @lianux-mm @wdfk-prog @xu18838022837

Changed Files (Click to expand)
  • src/thread.c
  • src/utest/thread_tc.c

📊 Current Review Status (Last Updated: 2026-10-17 16:04 CST)


📝 Review Instructions

  1. 维护者可以通过单击此处来刷新审查状态: 🔄 刷新状态
    Maintainers can refresh the review status by clicking here: 🔄 Refresh Status

  2. 确认审核通过后评论 LGTM/lgtm
    Comment LGTM/lgtm after confirming approval

  3. PR合并前需至少一位维护者确认
    PR must be confirmed by at least one maintainer before merging

ℹ️ 刷新CI状态操作需要具备仓库写入权限。
ℹ️ Refresh CI status operation requires repository Write permission.

@github-actions github-actions Bot added the Kernel PR has src relate code label Jun 26, 2026
@github-actions

github-actions Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report

at32f415-start

  • ROM: .text +80 B (+0.1%, 65,500 B / 262,144 B, total: 25% used)

esp32-c3

  • drom0_0_seg: .eh_frame +40 B, .eh_frame_hdr +8 B (+0.0%, 411,036 B / 8,388,576 B, total: 5% used)

gd32105r-start

  • CODE: .text +80 B (+0.1%, 69,416 B / 262,144 B, total: 26% used)

hc32f334

  • FLASH: .text +88 B (+0.1%, 99,680 B / 131,072 B, total: 76% used)

hpmicro-hpm5301evklite

  • DLM: .bss +16 B (+0.0%, 58,272 B / 130,304 B, total: 45% used)
  • ILM: .fast +144 B (+0.4%, 38,384 B / 131,072 B, total: 29% used)
  • XPI0: .fast +144 B (+0.1%, 125,144 B / 1,048,576 B, total: 12% used)

infineon-psoc6

  • flash: .text +76 B (+0.1%, 116,268 B / 262,144 B, total: 44% used)

k230

  • SRAM: .bss +32 B, .eh_frame +72 B (+0.0%, 1,128,643 B / 268,300,288 B, total: 0% used)

loongson-ls1cdev

  • Code: .text +184 B (+0.1%, 363,544 B)
  • Data: .bss +16 B (+0.0%, 59,828 B)

nordic-nrf51822

  • FLASH: .text +116 B (+0.2%, 52,152 B / 262,144 B, total: 20% used)
  • RAM: .bss +4 B (+0.1%, 2,720 B / 16,384 B, total: 17% used)

nuvoton-m487

  • CODE: .text +104 B (+0.0%, 356,280 B / 524,288 B, total: 68% used)
  • DATA: .bss +24 B (+0.0%, 101,956 B / 163,840 B, total: 62% used)

qemu-virt64-aarch64

  • Code: .eh_frame +32 B, .text +192 B (+0.0%, 1,078,036 B)

raspberry-pico-rp2040

  • FLASH: .text +104 B (+0.1%, 114,272 B / 2,097,152 B, total: 5% used)
  • RAM: .bss +4 B (+0.1%, 5,712 B / 262,144 B, total: 2% used)

renesas-ra2l1

  • FLASH: .text +76 B (+0.1%, 98,352 B / 262,144 B, total: 38% used)
  • RAM: .bss +8 B (+0.1%, 6,648 B / 32,768 B, total: 20% used)

simulator

  • Code: .eh_frame +32 B, .eh_frame_hdr +8 B, .rela.dyn +1,080 B, .rodata +192 B, .text +766 B (+0.1%, 2,675,098 B)
  • Data: .bss +32 B, .data +1,280 B (+0.1%, 1,610,596 B)

stm32f407-rt-spark

  • CODE: .text +76 B (+0.1%, 86,144 B / 1,048,576 B, total: 8% used)

stm32l475-atk-pandora-llvm

  • RAM1: .bss +8 B (+0.2%, 4,252 B / 98,304 B, total: 4% used)
  • ROM: .text +72 B (+0.1%, 82,760 B / 524,288 B, total: 16% used)

wch-ch32v208w-r0

  • FLASH: .text +136 B (+0.1%, 159,736 B / 491,520 B, total: 32% used)
  • RAM: .bss +8 B (+0.0%, 47,952 B / 65,536 B, total: 73% used)

x86

  • Code: .text +128 B (+0.1%, 199,053 B)
  • Data: .bss +64 B (+0.4%, 14,644 B)

xuantie-e901plus

  • DSRAM: .bss +4 B (+0.0%, 14,016 B / 524,288 B, total: 3% used)
  • ISRAM: .rodata +16 B, .text +48 B (+0.1%, 46,424 B / 131,072 B, total: 35% used)
    No memory changes detected for:
  • nxp-lpc1114

@Rbb666
Rbb666 requested a review from BernardXiong June 27, 2026 03:42

@BernardXiong BernardXiong left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review / 审查

结论 / Conclusion: no blocking issue found in the duplicate-defunct protection.

The new flag is initialized with the scheduler context, and _thread_mark_defunct() makes the check-and-set atomic under the thread spinlock before mutex detachment and defunct enqueue. This addresses the duplicate enqueue/double cleanup scenario described by the PR, and the change is small and localized.

建议 / Suggestions

  1. Please add an SMP-focused regression case, or document why the existing lock ordering is sufficient. The paths now combine the scheduler critical section, the thread spinlock, and mutex detachment; a test should exercise concurrent rt_thread_delete()/rt_thread_detach() against natural thread exit.

  2. The new bit lives in rt_sched_thread_ctx, whose other fields are generally accessed under scheduler-lock rules, while _thread_mark_defunct() uses the thread spinlock. Please add a short comment documenting that sched_flag_defunct is intentionally protected by thread->spinlock, so future scheduler changes do not introduce a lock-domain mismatch.

  3. Keep the negative return behavior covered for both dynamic and static threads after natural exit, including repeated calls. The current tests cover the main cases; the SMP/race case is the remaining useful gap.

The PR description and test intent are clear. / PR 描述和测试意图清晰。

@Rbb666

Rbb666 commented Oct 17, 2026

Copy link
Copy Markdown
Member Author

@BernardXiong 熊大,已经按照修改建议修复了

@Rbb666
Rbb666 force-pushed the defunct branch 2 times, most recently from 745bcd9 to ec6c0ec Compare October 17, 2026 08:04

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Kernel PR has src relate code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants