Skip to content

[components][libc][pthreads] fix race in lazy mutex initialization - #12107

Open
BernardXiong wants to merge 3 commits into
RT-Thread:masterfrom
BernardXiong:fix/pthread-mutex-lazy-init
Open

BernardXiong wants to merge 3 commits into
RT-Thread:masterfrom
BernardXiong:fix/pthread-mutex-lazy-init

Conversation

@BernardXiong

@BernardXiong BernardXiong commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

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

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

Mutexes declared with PTHREAD_MUTEX_INITIALIZER are initialized lazily by
pthread_mutex_lock(), pthread_mutex_trylock() and pthread_mutex_unlock().
Concurrent first use can cause multiple threads to initialize the same mutex,
or allow another thread to observe its attributes before the underlying
rt_mutex is ready. This can corrupt the mutex.

静态互斥锁在多线程首次并发使用时,可能重复初始化,或在底层锁尚未就绪时被访问。本 PR 修复这一延迟初始化竞态。

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

  • Modified file: components/libc/posix/pthreads/pthread_mutex.c only.
  • Use an atomic state transition from uninitialized (-1) to initializing
    (-2), so that exactly one thread performs lazy initialization.
  • Publish the attributes only after the underlying mutex has been initialized;
    other threads wait until initialization finishes.
  • Restore the uninitialized state on failure so a subsequent call can retry.
  • Make the mutex name counter atomic as well.
  • Keep the public pthread API and mutex structure unchanged.

通过原子状态机保证只有一个线程执行初始化,初始化成功后再发布属性;失败时恢复可重试状态,同时将锁名称计数器改为原子操作。

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

  • BSP: bsp/qemu-vexpress-a9.
  • .config: enable CONFIG_RT_USING_PTHREADS=y on top of the BSP default
    configuration, then generate rtconfig.h with scons --pyconfig-silent.
  • Local verification (December 2, 2026): scons -j8 passed with the pthread
    sources compiled. QEMU vexpress-a9 booted to the shell and successfully ran
    version, free and ps. This was a boot/shell smoke test, not a dedicated
    concurrent lazy-initialization stress test. No SD image was attached, so the
    BSP reported the expected SD mount warning during boot.
  • Formatting: checked the PR's changed lines with the repository's
    tools/ci/clang_format_check.py helpers and CI-pinned clang-format 22.1.8;
    the check and git diff --check passed.
  • action: Fork branch A9 build
    with CONFIG_RT_USING_PTHREADS=y (passed on commit d017c692d3), and
    PR CI checks.
  • Upstream CI on commit d017c692d3 completed successfully on December 2,
    2026: 115 check runs passed, 3 were skipped as expected, and the CLA status
    passed. There are no failed or pending checks.
  • Successful workflow results:
    format check,
    BSP builds,
    automated test matrix,
    static analysis.
  • No BSP is added by this PR; the final BSP-specific checklist item below
    does not apply.

当前拉取/合并请求的状态 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自查

Mutexes declared with PTHREAD_MUTEX_INITIALIZER are initialized lazily in
pthread_mutex_lock, pthread_mutex_trylock and pthread_mutex_unlock. When
several threads use such a mutex concurrently, they can all observe the
uninitialized state and initialize it at the same time. They can also
observe the attributes before the underlying rt_mutex is ready, which
corrupts the mutex.

Use an atomic state machine (-1 -> -2 -> attributes) so that only one
thread performs the initialization while the others wait until the
mutex is fully ready. Publish the attributes only after rt_mutex_init()
succeeds, and make the mutex name counter atomic as well.
@github-actions

github-actions Bot commented Dec 1, 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 分支 fix/pthread-mutex-lazy-init
    Enter PR branch fix/pthread-mutex-lazy-init 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.

完成后,提交将自动更新至 fix/pthread-mutex-lazy-init 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the fix/pthread-mutex-lazy-init 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 Dec 1, 2026 •

Copy link
Copy Markdown

📌 Code Review Assignment

🏷️ Tag: components

Reviewers: @Maihuanyi

Changed Files (Click to expand)
  • components/libc/posix/pthreads/pthread_mutex.c

🏷️ Tag: components_libc

Reviewers: @GorrayLi @mysterywolf

Changed Files (Click to expand)
  • components/libc/posix/pthreads/pthread_mutex.c

📊 Current Review Status (Last Updated: 2026-12-02 08:55 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 Dec 1, 2026 •

Copy link
Copy Markdown

Apply the CI-pinned clang-format style to the changed lazy initialization lines, including braces around conditional bodies. This resolves the PR format check without changing mutex behavior.
* initialized, so that a concurrent lazy initialization cannot observe
* a half-initialized mutex.
*/
rt_atomic_store(PTHREAD_MUTEX_ATTR(mutex),

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.

[P1] 用 release/acquire 发布初始化结果

ARM SMP 使用硬件原子后端时,rt_atomic_store/load 的 LDREX/STREX 没有内存屏障。另一核可能先看到 attr 已就绪,却读到尚未可见的 rt_mutex 初始化字段。请用 release 发布 attr,用 acquire 读取就绪状态,确保硬件后端也有对应屏障。

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

已在 7bdeefa 按建议处理:SMP 构建下,发布 attr 前调用 rt_hw_dmb() 作为 release 屏障,读取到就绪状态后再调用 rt_hw_dmb() 作为 acquire 屏障,不再依赖缺少内存序的硬件原子后端;单核构建不引入屏障。

验证:qemu-vexpress-a9 开启 RT_USING_SMP(2 核)和 RT_USING_PTHREADS,4 个线程各执行 10000 次 lock/unlock,计数为 40000,自测输出 PASS。

return EINVAL;
if (mutex->attr == -1)
/* lazy initialization for PTHREAD_MUTEX_INITIALIZER */
result = pthread_mutex_lazy_init(mutex);

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.

[P2] 保持 pthread_mutex_trylock() 非阻塞

另一线程正在初始化静态锁时,这里会进入 rt_thread_delay(1) 循环。请给初始化函数加非等待路径,遇到 INITIALIZING 立即返回 EBUSY,并在这里原样返回。

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

已在 7bdeefa 处理:pthread_mutex_lazy_init() 增加 wait 参数,pthread_mutex_trylock() 传入 RT_FALSE;遇到 INITIALIZING 时立即返回 EBUSY,不再进入 rt_thread_delay() 等待。

同一次 QEMU 自测中,持锁期间另一线程 trylock 返回 EBUSY,输出 PASS。

静态初始化的互斥锁在首次使用时惰性初始化。当前用 rt_atomic_store/load
发布和读取初始化状态,但部分硬件原子后端(如 ARM 的 LDREX/STREX)不提供
内存序,SMP 下另一核可能先看到状态就绪、却读到尚未初始化的 rt_mutex 字段。

- SMP 下在发布 attr 前加 release 屏障,读取到就绪状态后加 acquire 屏障;
  单核构建不加屏障;
- 为惰性初始化增加非等待路径,pthread_mutex_trylock() 遇到其他线程正在
  初始化时直接返回 EBUSY,不再进入 rt_thread_delay() 循环。

验证:qemu-vexpress-a9 开启 RT_USING_SMP(2 核)和 RT_USING_PTHREADS,
4 个线程各执行 10000 次 lock/unlock 后计数为 40000,trylock 返回 EBUSY,
自测输出 PASS。

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants