Skip to content

Commit 0004a6a

Browse files
committed
[add][thread]Add assertions for duplicate deletion across threads and warnings for incorrect usage.
1 parent db4fb4c commit 0004a6a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/thread.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,13 +482,40 @@ static rt_err_t _thread_detach(rt_thread_t thread)
482482
{
483483
rt_err_t error;
484484
rt_base_t critical_level;
485+
rt_uint8_t thread_status;
486+
rt_sched_lock_level_t slvl;
485487

486488
/**
487489
* forbid scheduling on current core before returning since current thread
488490
* may be detached from scheduler.
489491
*/
490492
critical_level = rt_enter_critical();
491493

494+
/* get thread status safely and perform safety checks before closing */
495+
rt_sched_lock(&slvl);
496+
thread_status = rt_sched_thread_get_stat(thread);
497+
498+
/* assert thread is not already closed to prevent duplicate deletion */
499+
RT_ASSERT(thread_status != RT_THREAD_CLOSE);
500+
501+
/* warn about unsafe deletion scenarios */
502+
if ((thread_status == RT_THREAD_RUNNING) || (thread_status == RT_THREAD_READY))
503+
{
504+
rt_sched_unlock(slvl);
505+
rt_exit_critical_safe(critical_level); /* exit critical before logging */
506+
507+
LOG_W("Warning: Deleting active thread [%s] in %s state may cause resource leak",
508+
thread->parent.name,
509+
(thread_status == RT_THREAD_RUNNING) ? "RUNNING" : "READY");
510+
511+
/* re-enter critical for the rest of the operation */
512+
critical_level = rt_enter_critical();
513+
}
514+
else
515+
{
516+
rt_sched_unlock(slvl);
517+
}
518+
492519
error = rt_thread_close(thread);
493520

494521
_thread_detach_from_mutex(thread);

0 commit comments

Comments
 (0)