rt-thread线程源码分析(二)

2014-11-24 07:57:45 · 作者: · 浏览: 1
const char *name,
void (*entry)(void *parameter),
void *parameter,
void *stack_start,
rt_uint32_t stack_size,
rt_uint8_t priority,
rt_uint32_t tick)
{
/* init thread list */
rt_list_init(&(thread->tlist));//初始化线程节点
thread->entry = (void *)entry;//入口函数
thread->parameter = parameter;//入口函数的参数
/* stack init */
thread->stack_addr = stack_start;//栈地址
thread->stack_size = (rt_uint16_t)stack_size;//栈大小
/* init thread stack */
rt_memset(thread->stack_addr, '#', thread->stack_size);//将栈内的所有字节初始化为'#'号
thread->sp = (void *)rt_hw_stack_init(thread->entry, thread->parameter,//初始化时设置sp的内容,rt_hw_stack_init是一个与具体MCU相关的函数,这里就不做介绍
(void *)((char *)thread->stack_addr + thread->stack_size - 4),
(void *)rt_thread_exit);
/* priority init */
RT_ASSERT(priority < RT_THREAD_PRIORITY_MAX);
thread->init_priority = priority;//当前优先级和初始化优先级设置
thread->current_priority = priority;
/* tick init */
thread->init_tick = tick;//初始化tick和剩余tick
thread->remaining_tick = tick;
/* error and flags */
thread->error = RT_EOK;//错误的状态,线程状态初始化时为RT_THREAD_INIT
thread->stat = RT_THREAD_INIT;
/* initialize cleanup function and user data */
thread->cleanup = 0;//线程析构函数及其参数
thread->user_data = 0;
/* init thread timer */
rt_timer_init(&(thread->thread_timer),//初始化线程的定时器
thread->name,
rt_thread_timeout,
thread,
0,
RT_TIMER_FLAG_ONE_SHOT);
return RT_EOK;
}
其中rt_thread_timeout的函数如下定义:
[cpp]
/**
* This function is the timeout function for thread, normally which is invoked
* when thread is timeout to wait some resource.
*
* @param parameter the parameter of thread timeout function
*/
void rt_thread_timeout(void *parameter)
{
struct rt_thread *thread;
thread = (struct rt_thread *)parameter;
/* thread check */
RT_ASSERT(thread != RT_NULL);
RT_ASSERT(thread->stat == RT_THREAD_SUSPEND);
/* set error number */
thread->error = -RT_ETIMEOUT;
/* remove from suspend list *///从挂起链表中移除
rt_list_remove(&(thread->tlist));
/* insert to schedule ready list */
rt_schedule_insert_thread(thread);//加入调度器
/* do schedule */
rt_schedule();//重新调度
}
2.2 创建线程
[cpp]
/**
* This function will create a thread object and allocate thread object memory
* and stack.
*
* @param name the name of thread, which shall be unique
* @param entry the entry function of thread
* @param parameter the parameter of thread enter function
* @param stack_size the size of thread stack
* @param priority the priority of thread
* @param tick the time slice if there are same priority thread
*
* @return the created thread object
*/
rt_thread_t rt_thread_create(const char *name,
void (*entry)(void *parameter),
void *parameter,
rt_uint32_t sta