3030 * 2022-01-07 Gabriel Moving __on_rt_xxxxx_hook to scheduler.c
3131 * 2023-03-27 rose_man Split into scheduler upc and scheduler_mp.c
3232 * 2023-10-17 ChuShicheng Modify the timing of clearing RT_THREAD_STAT_YIELD flag bits
33+ * 2025-08-04 Pillar Add rt_scheduler_critical_switch_flag
3334 */
3435
3536#define __RT_IPC_SOURCE__
@@ -49,6 +50,7 @@ rt_uint8_t rt_thread_ready_table[32];
4950
5051extern volatile rt_atomic_t rt_interrupt_nest ;
5152static rt_int16_t rt_scheduler_lock_nest ;
53+ static rt_int8_t rt_scheduler_critical_switch_flag = -1 ;
5254rt_uint8_t rt_current_priority ;
5355
5456#if defined(RT_USING_HOOK ) && defined(RT_HOOK_USING_FUNC_PTR )
@@ -235,6 +237,7 @@ void rt_system_scheduler_start(void)
235237 to_thread = _scheduler_get_highest_priority_thread (& highest_ready_priority );
236238
237239 rt_cpu_self ()-> current_thread = to_thread ;
240+ rt_scheduler_critical_switch_flag = 0 ;
238241
239242 rt_sched_remove_thread (to_thread );
240243 RT_SCHED_CTX (to_thread ).stat = RT_THREAD_RUNNING ;
@@ -387,6 +390,10 @@ void rt_schedule(void)
387390 }
388391 }
389392 }
393+ else
394+ {
395+ rt_scheduler_critical_switch_flag = 1 ;
396+ }
390397
391398 /* enable interrupt */
392399 rt_hw_interrupt_enable (level );
@@ -604,6 +611,7 @@ void rt_exit_critical_safe(rt_base_t critical_level)
604611
605612/**
606613 * @brief Safely exit critical section (non-debug version)
614+ * If the scheduling function is called before exiting, it will be scheduled in this function.
607615 *
608616 * @param critical_level The expected critical level (unused in non-debug build)
609617 *
@@ -657,6 +665,7 @@ RTM_EXPORT(rt_enter_critical);
657665
658666/**
659667 * @brief Exit critical section and unlock scheduler
668+ * If the scheduling function is called before exiting, it will be scheduled in this function.
660669 *
661670 * @details This function:
662671 * - Decrements the scheduler lock nesting count
@@ -685,9 +694,10 @@ void rt_exit_critical(void)
685694 /* enable interrupt */
686695 rt_hw_interrupt_enable (level );
687696
688- if (rt_current_thread )
697+ if (rt_scheduler_critical_switch_flag == 1 )
689698 {
690- /* if scheduler is started, do a schedule */
699+ rt_scheduler_critical_switch_flag = 0 ;
700+ /* if scheduler is started and needs to be scheduled, do a schedule */
691701 rt_schedule ();
692702 }
693703 }
0 commit comments