rt-thread线程源码分析(四)
rted
*
* @return the operation status, RT_EOK on OK, -RT_ERROR on error
*/
rt_err_t rt_thread_startup(rt_thread_t thread)
{
/* thread check *///参数检查
RT_ASSERT(thread != RT_NULL);
RT_ASSERT(thread->stat == RT_THREAD_INIT);
/* set current priority to init priority */
thread->current_priority = thread->init_priority;//启动线程时将线程当前的优先级设置为初始优先级
/* calculate priority attribute */
#if RT_THREAD_PRIORITY_MAX > 32
thread->number = thread->current_priority >> 3; /* 5bit */
thread->number_mask = 1L << thread->number;
thread->high_mask = 1L << (thread->current_priority & 0x07); /* 3bit */
#else
thread->number_mask = 1L << thread->current_priority;
#endif
RT_DEBUG_LOG(RT_DEBUG_THREAD, ("startup a thread:%s with priority:%d\n",
thread->name, thread->init_priority));
/* change thread stat */
thread->stat = RT_THREAD_SUSPEND;//将线程的状态设置为RT_THREAD_SUSPEND
/* then resume it */
rt_thread_resume(thread);//还原线程
if (rt_thread_self() != RT_NULL)//如果当前的线程不为空,则执行线程调度操作
{
/* do a scheduling */
rt_schedule();
}
return RT_EOK;
}
其中rt_thread_self函数如下定义:
[cpp]
/**
* This function will return self thread object
*
* @return the self thread object
*/
rt_thread_t rt_thread_self(void)
{
return rt_current_thread;
}
rt_current_thread为全局变量,保存当前正在运行的线程。
rt_thread_resume函数见后第6章内容,rt_schedule函数见线程调度
源码分析相关章节.
5 线程挂起
[cpp]
/**
* This function will suspend the specified thread.
*
* @param thread the thread to be suspended
*
* @return the operation status, RT_EOK on OK, -RT_ERROR on error
*
* @note if suspend self thread, after this function call, the
* rt_schedule() must be invoked.
*/
rt_err_t rt_thread_suspend(rt_thread_t thread)
{
register rt_base_t temp;
/* thread check */
RT_ASSERT(thread != RT_NULL);
RT_DEBUG_LOG(RT_DEBUG_THREAD, ("thread suspend: %s\n", thread->name));
if (thread->stat != RT_THREAD_READY)//此函数只对处于就绪状态的线程操作
{
RT_DEBUG_LOG(RT_DEBUG_THREAD, ("thread suspend: thread disorder, %d\n",
thread->stat));
return -RT_ERROR;
}
/* disable interrupt */
temp = rt_hw_interrupt_disable();//关中断
/* change thread stat */
thread->stat = RT_THREAD_SUSPEND;//将线程设置为挂起状态
rt_schedule_remove_thread(thread);//将线程从调试器中移除
/* enable interrupt */
rt_hw_interrupt_enable(temp);//开中断
return RT_EOK;
}
有关rt_schedule_remove_thread函数见后续在前调度器源码分析的文章。
6 线程还原
[cpp]
/**
* This function will resume a thread and put it to system ready queue.
*
* @param thread the thread to be resumed
*
* @return the operation status, RT_EOK on OK, -RT_ERROR on error
*/
rt_err_t rt_thread_resume(rt_thread_t thread)
{
register rt_base_t temp;
/* thread check */
RT_ASSERT(thread != RT_NULL);
RT_DEBUG_LOG(RT_DEBUG_THREAD, ("thread resume: %s\n", thread->name));
if (thread->stat != RT_THREAD_SUSPEND)//只对处于挂起的线程进行还原操作
{
RT_DEBUG_LOG(RT_DEBUG_THREAD