1 空闲线程的实现
在rt-thread线程启运时,
系统会初始化空闲线程并启动它:
[cpp]
/**
* @ingroup SymstemInit
*
* This function will initialize idle thread, then start it.
*
* @note this function must be invoked when system init.
*/
void rt_thread_idle_init(void)
{
/* initialize thread */
rt_thread_init(&idle,
"tidle",
rt_thread_idle_entry,
RT_NULL,
&rt_thread_stack[0],
sizeof(rt_thread_stack),
RT_THREAD_PRIORITY_MAX - 1,
32);
/* startup */
rt_thread_startup(&idle);
}
由上可见,空闲线程的优先级为RT_THREAD_PRIORITY_MAX-1,即用户定义最多优先级-1,也就是最低优先级了。接下来看空闲线程的入口函数:
[cpp]
static void rt_thread_idle_entry(void *parameter)
{
while (1)
{
#ifdef RT_USING_HOOK
if (rt_thread_idle_hook != RT_NULL)
rt_thread_idle_hook();
#endif
rt_thread_idle_excute();
}
}
空闲线程不断是执行rt_thread_idle_excute,其实现如下:
[cpp]
/**
* @ingroup Thread
*
* This function will perform system background job when system idle.
*/
void rt_thread_idle_excute(void)
{
/* check the defunct thread list */
if (!rt_list_isempty(&rt_thread_defunct))//判断rt_thread_defunct是否为空
{
rt_base_t lock;
rt_thread_t thread;
#ifdef RT_USING_MODULE
rt_module_t module = RT_NULL;
#endif
RT_DEBUG_NOT_IN_INTERRUPT;//确保此函数不是在中断中执行
/* disable interrupt */
lock = rt_hw_interrupt_disable();//开中断
/* re-check whether list is empty */
if (!rt_list_isempty(&rt_thread_defunct))//再次判断rt_thread_defunct是否为空
{
/* get defunct thread */
thread = rt_list_entry(rt_thread_defunct.next,//获取等回收的线程
struct rt_thread,
tlist);
#ifdef RT_USING_MODULE
/* get thread's parent module */
module = (rt_module_t)thread->module_id;//得到模块
/* if the thread is module's main thread */
if (module != RT_NULL && module->module_thread == thread)//清空模块线程
{
/* detach module's main thread */
module->module_thread = RT_NULL;
}
#endif
/* remove defunct thread */
rt_list_remove(&(thread->tlist));//将线程从回收链表中移除
/* invoke thread cleanup */
if (thread->cleanup != RT_NULL)//执行析构函数
thread->cleanup(thread);
/* if it's a system object, not delete it */
if (rt_object_is_systemobject((rt_object_t)thread) == RT_TRUE)//如果为系统线程
{
/* enable interrupt */
rt_hw_interrupt_enable(lock);//开中断
return;
}
}
else
{
/* enable interrupt */
rt_hw_interrupt_enable(lock);//开中断
/* may the defunct thread list is removed by others, just return */
return;
}
/* enable interrupt */
rt_hw_interrupt_enable(lock);//开中断
#ifdef RT_USING_HEAP
#if defined(RT_USING_MODULE) && defined(RT_USING_SLAB)
/* the thread belongs to an application mo