曾经,在论坛里跟某小伙伴探讨问题,说到 rt-thread 中的中断操作太频繁了。当时粗略看了一眼,虽然有怀疑,但也没发现 idle 线程里不合理的地方。
经过上篇对僵尸线程的销毁流程的梳理,才发现 idle 线程是可以做到更“空闲”的。
想清楚了 idle 线程的这点儿特性后,接下来就容量理解了。
如下,无僵尸线程情况下的最简化代码,
static void rt_defunct_execute(void)
{
while (1)
{
rt_base_t lock;
rt_thread_t thread;
void (*cleanup)(struct rt_thread *tid);
/* disable interrupt */
lock = rt_hw_interrupt_disable();
thread = rt_thread_defunct_dequeue();
if (!thread)
{
rt_hw_interrupt_enable(lock);
break;
}
...
}
}
static void rt_thread_idle_entry(void *parameter)
{
while (1)
{
rt_defunct_execute();
}
}
rt_thread_idle_entry
线程入口函数里一个 while 循环调用 rt_defunct_execute
,rt_defunct_execute
函数里另一个 while 循环。继续往下看 rt_defunct_execute
函数的其它操作,销毁僵尸线程的过程还有一次关开中断操作。经过仔细分析 rt_defunct_execute
其中的所有关中断操作都可以删掉。
简化后的代码如下:
static void rt_defunct_execute(void)
{
/* Loop until there is no dead thread. So one call to rt_defunct_execute
* will do all the cleanups. */
while (1)
{
rt_thread_t thread;
void (*cleanup)(struct rt_thread *tid);
#ifdef RT_USING_MODULE
struct rt_dlmodule *module = RT_NULL;
#endif
/* get defunct thread */
thread = rt_thread_defunct_dequeue();
if (thread == RT_NULL)
{
break;
}
#ifdef RT_USING_MODULE
module = (struct rt_dlmodule*)thread->module_id;
if (module)
{
dlmodule_destroy(module);
}
#else
#endif
/* invoke thread cleanup */
cleanup = thread->cleanup;
if (cleanup != RT_NULL)
{
cleanup(thread);
}
#ifdef RT_USING_SIGNALS
rt_thread_free_sig(thread);
#endif
/* if it's a system object, not delete it */
if (rt_object_is_systemobject((rt_object_t)thread) == RT_TRUE)
{
/* detach this object */
rt_object_detach((rt_object_t)thread);
}
else
{
#ifdef RT_USING_HEAP
/* release thread's stack */
RT_KERNEL_FREE(thread->stack_addr);
/* delete thread object */
rt_object_delete((rt_object_t)thread);
#endif
}
}
}
rt_defunct_execute
函数中的所有中断操作全删掉。唯一需要关中断的地方是 rt_thread_defunct_dequeue
内部,
if (l->next != l)
{
thread = rt_list_entry(l->next,
struct rt_thread,
tlist);
/* disable interrupt */
level = rt_hw_interrupt_disable();
rt_list_remove(&(thread->tlist));
rt_hw_interrupt_enable(level);
}
粗略估算 rt_defunct_execute
函数的执行时间砍半,这一指标没什么特别的,重要的是: 在没有任何线程退出的情况下,idle 线程里不需要任何关中断操作!!! idle 线程更“空闲”了。
本系列文章均个人原创,难免有疏漏之处,欢迎各位小伙伴指正。
相关文章:
rt-thread 系统优化系列(一) 之 关中断
rt-thread 系统优化系列(二) 之 线程间同步和通信对中断的影响
rt-thread 系统优化系列(三) 之 软定时器
rt-thread 系统优化系列(四) 之 再谈 ipc 中的 bug
rt-thread 系统优化系列(五) 之 线程销毁谜题
rt-thread 系统优化系列(六) 之 让 idle 线程闲下来
@RT-Thread小师弟 @aozima 这黑白配色太吓人了
@chenyaxing 辣眼睛,有一段时间了,期间还有过白底灰字,看不清楚的。我感觉他们调配色调一半去干其它工作了。
@出出啊 哈哈 💣