smp: ensure safe thread termination in rt_thread_close #10549
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
拉取/合并请求描述:(PR description)
确保smp环境下 rt_thread_close 能真正关闭并停止目标线程的运行,可参考问题: #10554
[
为什么提交这份PR (why to submit this PR)
在SMP环境下,当一个运行在一个核心上的线程通过rt_thread_close和rt_thread_detach间接调用rt_thread_close试图关闭另一个核心上运行的线程时可能会存在潜在问题。具体而言,
rt_thread_close
的操作逻辑仅是将目标线程的控制块从调度队列中移除,并将其状态标记为关闭,但这一操作并不能立即终止目标线程的实际执行。由于目标线程可能仍在另一个核心上运行,它无法实时感知到自身的关闭状态,只有下次触发调度时才会真正脱离CPU。这种延迟会导致关键问题:在rt_thread_close调用完成后,目标线程可能仍在执行代码,从而引发并发访问冲突或资源竞争等问题。
你的解决方案是什么 (what is your solution)
本pr的修改只会影响smp环境下的两条调用链:
rt_thread_delete -> _thread_detach -> rt_thread_close
rt_thread_detach -> _thread_detach -> rt_thread_close
不会影响线程通过 _thread_exit -> _thread_detach -> rt_thread_close 关闭自己的调用链
在rt_thread_close的实现中,当目标线程被标记为关闭状态后,如果其运行的核心与当前核心不同,系统会向其所在核心发送核间中断,以尽快触发该核心的重新调度,从而确保目标线程能够及时脱离 CPU 并真正停止执行。
而在 rt_thread_delete
和 rt_thread_detach
中,由于当前核心的调度已被 rt_enter_critical 禁用,因此采用轮询机制检测目标线程是否已完全脱离 CPU。为了应对目标核心始终无法调度的极端情况,设置了超时机制。该超时时间应该与硬件平台性能和系统负载相关,目前暂采RT_SMP_THREAD_DETACH_TIMEOUT宏进行配置。请提供验证的bsp和config (provide the config and bsp)
]
当前拉取/合并请求的状态 Intent for your PR
必须选择一项 Choose one (Mandatory):
代码质量 Code Quality:
我在这个拉取/合并请求中已经考虑了 As part of this pull request, I've considered the following:
#if 0
代码,不包含已经被注释了的代码 All redundant code is removed and cleaned up