Skip to content

[utest][atomic] release the worker threads and the semaphore between runs - #12033

Merged
Rbb666 merged 2 commits into
RT-Thread:masterfrom
Yunlk:test/atomic-tc-no-leak
Nov 13, 2026
Merged

Rbb666 merged 2 commits into
RT-Thread:masterfrom
Yunlk:test/atomic-tc-no-leak

Conversation

@Yunlk

@Yunlk Yunlk commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

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

[

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

用 #11983 的多轮自动运行功能跑 utest 时发现 core.atomic 每轮泄漏,而且有两种表现。

test_atomic_add() 每轮创建 1 个信号量和 3 个动态线程,一个都没有释放:

sem_t = rt_sem_create("atomic_sem", 0, RT_IPC_FLAG_PRIO);
thread = rt_thread_create("t1", ture_entry, ...);
...
for (i = 0; i < 3; i++) rt_sem_take(sem_t, RT_WAITING_FOREVER);
/* 到这里返回,sem_t 和三个线程都没有收尾 */

两种泄漏:

  1. 三个 worker 退出后回收不了。它们 release 完信号量就返回,TCB 和栈要等 rt_defunct_execute() 才释放,而它跑在 idle 线程里。这个用例的 worker 是纯忙循环、utest 线程只阻塞在 rt_sem_take 上,idle(优先级 255)全程没有机会被调度,于是每轮堆下 3 个已退出的线程。
  2. 信号量从未删除。

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

在返回前让出一次 CPU(让 defunct 队列被处理),再删除信号量:

rt_thread_mdelay(1);
rt_sem_delete(sem_t);
sem_t = RT_NULL;

rt_thread_mdelay(1) 这个约定在 src/utest/hooklist_tc.c:88-91 已有先例(那里注释写明是等 rt_defunct_execute() 摘除线程对象)。

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

  • BSP: bsp/qemu-vexpress-a9
  • .config: RT_USING_UTESTCASES=y + RT_UTEST_USING_AUTO_RUN=y + RT_UTEST_AUTO_RUN_LOOP=3
  • action: 未使用 GitHub Actions;本地 QEMU 11.0.0 + arm-none-eabi-gcc 15.2.1,master 5caa519be

用例单独跑:线程累积

修改前
[I/utest] loop 1/3 runtime info   used : 63608   ps: t1/t2/t3 残留 3 个 (status close)
[I/utest] loop 2/3 runtime info   used : 88848   ps: t1/t2/t3 残留 6 个
[I/utest] loop 3/3 runtime info   used : 114088  ps: t1/t2/t3 残留 9 个
                                            (+25240 每轮 ≈ 3 × 8192 栈 + TCB)

修改后
[I/utest] loop 1/3 runtime info   used : 38368   ps: 残留 0 个
[I/utest] loop 2/3 runtime info   used : 38368   ps: 残留 0 个
[I/utest] loop 3/3 runtime info   used : 38368   ps: 残留 0 个

与其他用例一起跑:只剩信号量泄漏

{core.semaphore, core.ipc_event, core.atomic} 一起跑时,中间有其他用例让 idle 拿到 CPU,线程能被回收,但信号量仍在漏:

修改前  used: 38440 -> 38504 -> 38568   (+64 每轮)
修改后  used: 38376 -> 38376 -> 38376

64 字节正好接近 sizeof(struct rt_semaphore)。

这说明多轮运行时会看到两种量级完全不同的泄漏:只用例单跑,泄漏被线程累积掩盖成 25 KB/轮;与别的用例混跑,则表现为稳定的 64 字节/轮。任何一条单独看都可能被当成噪声忽略。

关于 #11983

这两处能发现,直接得益于 #11983 新加的 RT_UTEST_AUTO_RUN_LOOP 与每轮 free/ps 采样。顺带确认一件事:采样动作本身不泄漏——我单独把 msh_exec("free") + msh_exec("ps") 连跑三轮,used 稳定在 39824 不变,所以上面的增长不是观测行为引入的。

]

当前拉取/合并请求的状态 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
  • 已经使用clang-format 源码格式化工具确保格式符合RT-Thread代码规范 This PR has been formatted with clang-format and complies with RT-Thread code specification
  • 如果是新增bsp, 已经添加ci检查到.github/ALL_BSP_COMPILE.json 详细请参考链接BSP自查

…runs

test_atomic_add() creates one semaphore and three dynamic threads per run and
released neither. Two separate leaks came out of that:

1. The three workers exit right after releasing the semaphore, so their TCB and
   stack are only reclaimed once rt_defunct_execute() runs. That runs in the idle
   thread, and the idle thread never gets scheduled while this testcase keeps a
   runnable thread around. Running the testcase repeatedly in one boot therefore
   accumulates dead threads.

2. The semaphore was never deleted.

Measured on bsp/qemu-vexpress-a9 with RT_UTEST_AUTO_RUN_LOOP=3, sampling the
thread list and the heap after every loop.

core.atomic alone:

    before   used 63608 -> 88848 -> 114088   (+25240 per run)
             ps shows 3 -> 6 -> 9 lingering t1/t2/t3 threads, status "close"
    after    used 38368 -> 38368 -> 38368
             ps shows 0 lingering threads each loop

{semaphore, event, atomic} together, where the idle thread does get a chance to
run between testcases and only the semaphore leak was visible:

    before   used 38440 -> 38504 -> 38568    (+64 per run, sizeof(rt_semaphore))
    after    used 38376 -> 38376 -> 38376

The fix is a yield before returning, so the defunct queue is processed, plus
rt_sem_delete(). The yield follows the same convention as hooklist_tc.c, which
waits for rt_defunct_execute() to detach the thread object.

Refs RT-Thread#11963
Refs RT-Thread#11983
@github-actions github-actions Bot added the Kernel PR has src relate code label Nov 11, 2026
@github-actions

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 分支 test/atomic-tc-no-leak
    Enter PR branch test/atomic-tc-no-leak 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.

完成后,提交将自动更新至 test/atomic-tc-no-leak 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the test/atomic-tc-no-leak 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 Nov 11, 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/utest/atomic_tc.c

📊 Current Review Status (Last Updated: 2026-11-12 16:42 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 commented Nov 11, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

at32f415-start

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

esp32-c3

  • dram0_0_seg: .dram0.data +36 B, .stack +4 B (+0.0%, 216,832 B / 325,120 B, total: 67% used)

gd32105r-start

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

hc32f334

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

hpmicro-hpm5100evk

  • ILM: .fast +32 B (+0.1%, 42,672 B / 262,144 B, total: 16% used)
  • XPI0: .fast +32 B (+0.0%, 102,956 B / 1,048,576 B, total: 10% used)

infineon-psoc6

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

loongson-ls1cdev

  • Code: .text +84 B (+0.0%, 363,492 B)

nordic-nrf51822

  • FLASH: .text +60 B (+0.1%, 52,116 B / 262,144 B, total: 20% used)

nuvoton-m487

  • CODE: .text +52 B (+0.0%, 356,632 B / 524,288 B, total: 68% used)

qemu-virt64-aarch64

  • Code: .text +112 B (+0.0%, 1,009,868 B)

raspberry-pico-rp2040

  • FLASH: .rodata +40 B, .text +24 B (+0.1%, 114,256 B / 2,097,152 B, total: 5% used)

renesas-ra2l1

  • FLASH: .text +60 B (+0.1%, 98,364 B / 262,144 B, total: 38% used)

simulator

  • Code: .rela.dyn +648 B, .rodata +128 B, .text +309 B (+0.0%, 2,674,143 B)
  • Data: .data +768 B (+0.0%, 1,609,796 B)

stm32f407-rt-spark

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

stm32l475-atk-pandora-llvm

  • ROM: .text +56 B (+0.1%, 82,768 B / 524,288 B, total: 16% used)

wch-ch32v208w-r0

  • FLASH: .text +64 B (+0.0%, 159,952 B / 491,520 B, total: 33% used)

x86

  • Code: .rodata +32 B, .text +32 B (+0.0%, 199,005 B)

xuantie-e901plus

  • ISRAM: .rodata +64 B (+0.1%, 46,488 B / 131,072 B, total: 35% used)

No memory changes detected for:


Catch memory regressions in CI with MemBrowse. Free for open source.

The comment claimed the yield "waits for the idle thread". rt_thread_mdelay()
does not wait for anything specific: _thread_sleep() suspends the calling thread
and reschedules, so the CPU goes to whatever else is ready. Reaching the idle
thread is a consequence of giving up the CPU, not something the call targets.

That distinction matters when reviewing the fix: it does not depend on idle being
scheduled promptly, only on this thread stepping out of the ready queue, which
_thread_sleep() does unconditionally.

Also record both measured deltas so the constant is checkable:
UTEST_THR_STACK_SIZE = 4096 gives 12952 bytes per run, 8192 gives 25240, and both
reduce to the same rt_thread size of about 221 bytes.
@Yunlk

Yunlk commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

补一组十轮数据和一条对修法的自我质疑,另外更正了注释里一句不准确的话(提交 936b74131,纯注释改动)。

十轮:严格线性,零抖动

RT_UTEST_AUTO_RUN_LOOP=10,只启用 RT_UTEST_ATOMIC:

轮次 used 与上一轮之差
1 47224 —
2 60176 +12952
3 73128 +12952
4 86080 +12952
5 99032 +12952
6 111984 +12952
7 124936 +12952
8 137888 +12952
9 150840 +12952
10 163792 +12952

九次增量完全相等,没有任何波动。这排除了"首次初始化固定开销"的可能——那就是每轮泄漏。

ps 里的残留线程数严格 3 → 6 → 9 → … → 30,每轮 +3。

和 PR 描述里 25240 的差异:配置不同,不是测量误差

PR 描述里写的是 +25240/轮,这里量到 +12952/轮。原因只有一个:

本次:UTEST_THR_STACK_SIZE = 4096  →  3 × (4096 + 221.3) = 12952
先前:UTEST_THR_STACK_SIZE = 8192  →  3 × (8192 + 221.3) = 25240

两组数据反算出的 TCB 大小都是 221.3 字节,完全一致。所以泄漏模型 3 × (栈 + TCB) 是成立的,数字差异纯粹来自 UTEST_THR_STACK_SIZE 配置(先前那次我手动设成了 8192,这次用的是 BSP 默认 4096)。

这一点值得记录:这条泄漏的绝对量取决于配置,但"每轮 3 个线程"这个事实与配置无关。评审时如果只对比绝对数字会觉得对不上,对比"线程数增量"就一目了然。

自我质疑:rt_thread_mdelay(1) 真的等得到 idle 吗

我原来的注释写的是"让 idle 线程有机会被调度",这个说法不准确。查了 src/thread.c:656-710 的 _thread_sleep():

critical_level = rt_enter_critical();
err = rt_thread_suspend_with_flag(thread, RT_INTERRUPTIBLE);   /* 先把调用者自己摘下就绪队列 */
if (err == RT_EOK)
{
    rt_timer_control(&(thread->thread_timer), RT_TIMER_CTRL_SET_TIME, &tick);
    rt_timer_start(&(thread->thread_timer));
    rt_schedule();      /* 自己已不在就绪队列,必然切走 */
}

rt_thread_mdelay() 的语义是"挂起调用者一个 tick 并重新调度",不是"等待 idle 被调度"。 它不针对任何特定线程——只是让出 CPU。

这个区别在评审时很重要:修法的正确性不依赖"idle 会被及时调度",只依赖"当前线程会离开就绪队列",而 _thread_sleep() 是无条件这么做的。

一个真实的边界情况

即使 vacate CPU 是确定的,仍有理论上的边角:如果 mdelay(1) 到期后测试线程抢不回 CPU(存在同优先级或更高优先级的忙循环线程),那么这次 rt_sem_delete() 会在延迟返回后才执行。

不过这种情况下 idle 反而更容易拿到 CPU——defunct 队列照样会被清理。所以泄漏不会复发,最坏是这次调用返回得晚一些。

真正会失效的场景是"低优先级线程被饿死"(starvation),但那是系统级调度问题,不该由这个测试用例负责。

建议

如果维护者希望这个 fix 更"硬"一点,可以不用 mdelay 而改成有界等待:

for (i = 0; i < 100 && rt_thread_find("t1") != RT_NULL; i++)
{
    rt_thread_mdelay(1);
}

这样即使第一次 tick 没让 defunct 跑完也会重试。我没有直接这么改,是因为 hooklist_tc.c 的既有约定就是单次 mdelay(1),保持一致更重要;但如果维护者认为需要,我可以改成有界轮询。

验证配置

  • BSP: bsp/qemu-vexpress-a9
  • .config: RT_USING_UTESTCASES=y + RT_UTEST_USING_AUTO_RUN=y + RT_UTEST_AUTO_RUN_LOOP=10 + RT_UTEST_ATOMIC=y,其余 utest 项关闭
  • UTEST_THR_STACK_SIZE=4096(BSP 默认)
  • QEMU 11.0.0 + arm-none-eabi-gcc 15.2.1,master 5caa519be

@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.

批准。 复核 head 936b7413:断言后先 rt_thread_mdelay(1) 让 idle 线程回收 defunct 队列中的 3 个 worker,再删除信号量,修复了每轮 3 个线程加 1 个信号量的泄漏;做法与 hooklist_tc.c 的既有约定一致。CI 全绿(108 成功)。

Approved. The test now yields once so the idle thread can reap the three exited workers before deleting the semaphore, matching the existing convention in hooklist_tc.c. CI is green.

@Rbb666
Rbb666 merged commit 21834bf into RT-Thread:master Nov 13, 2026
115 checks passed
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.

3 participants