RT-Thread线程管理

RT-Thread是一个支持多任务的操作系统,其线程管理基于抢占式调度,提供系统线程和用户线程。线程控制块是线程管理的基础,包含了线程信息和上下文。线程具有独立栈,状态包括就绪、运行、阻塞等。调度器按优先级选择线程,高优先级可抢占低优先级。线程相关操作包括创建、删除、启动、睡眠等。此外,还支持线程间切换、钩子函数设置等功能。
摘要由CSDN通过智能技术生成

      RT-Thread是支持多任务的操作系统,多任务是通过多线程的方式实现。线程是任务的载体,是RTT中最基本的调度单位。线程在运行的时候,它自己会认为独占CPU运行线程执行时的运行环境称为上下文,具体来说就是各个变量和数据,包括所有的寄存器变量、堆栈、内存信息等。

1 线程管理特点

       RT-Thread 线程管理的主要功能是对线程进行管理和调度,系统中总共存在两类线程,分别是系统线程和用户线程,系统线程是由 RT-Thread 内核创建的线程,用户线程是由应用程序创建的线程,这两类线程都会从内核对象容器中分配线程对象,当线程被删除时,也会被从对象容器中删除。

        RT-Thread 的线程调度器是抢占式的,主要的工作就是从就绪线程列表中查找最高优先级线就程,保证最高优先级的线程能够被运行,最高优先级的任务一旦就绪,总能得到 CPU 的使用权。

     当调度器调度线程切换时,先将当前线程上下文保存起来,当再切回到这个线程时,线程调度器将该线程的上下文信息恢复。

2 线程工作机制

2.1 线程控制块

        线程控制块由结构体 struct rt_thread 表示,线程控制块是操作系统用于管理线程的一个数据结构,它会存放线程的一些信息,例如优先级、线程名称、线程状态等,也包含线程与线程之间连接用的链表结构,线程等待事件集合等。

struct rt_thread
{
    /* rt object */
    char        name[RT_NAME_MAX];       /**< the name of thread */
    rt_uint8_t  type;               /**< type of object */
    rt_uint8_t  flags;               /**< thread's flags */

    rt_list_t   list;                    /**< the object list */
    rt_list_t   tlist;                   /**< the thread list */

    /* stack point and entry */
    void       *sp;                     /**< stack point 栈指针*/  
    void       *entry;                 /**< entry */
    void       *parameter;          /**< parameter */
    void       *stack_addr;         /**< stack address point 栈地址指针*/
    rt_uint32_t stack_size;       /**< stack size */

    /* error code */
    rt_err_t    error;                   /**< error code */
    rt_uint8_t  stat;                    /**< thread status 线程状态*/

    /* priority */
    rt_uint8_t  current_priority;        /**< current priority */
    rt_uint8_t  init_priority;           /**< initialized priority */

    rt_uint32_t number_mask;

    ...

    rt_ubase_t  init_tick;                          /**< thread's initialized tick */
    rt_ubase_t  remaining_tick;                /**< remaining tick */

    struct rt_timer thread_timer;              /**< built-in thread timer */

    void (*cleanup)(struct rt_thread *tid);    /**< cleanup function when thread exit */

    rt_uint32_t user_data;                          /**< private user data beyond this thread */
};

注:cleanup函数指针指向的函数,会在线程退出的时候,被idle线程回调一次,执行用户设置的清理现场等工作。

2.2线程属性

1 线程栈

       RT-Thread 线程具有独立的栈,当进行线程切换时,会将当前线程的上下文存在栈中,当线程要恢复运行时,再从栈中读取上下文信息,进行恢复。

2 线程状态

注:阻塞、非阻塞、同步与异步的概念

同步:指下一步操作必须是在上一步操作得到回应之后得以执行,这次期间系统处于等待状态,无法进行其他操作。
示意图: 执行操作——>等待结果——>继续操作
异步:指不管上一步操作是否得到回应都可以继续进行其他操作,在得到回应之后再进行下一步操作。
示意图: 执行操作——>等待结果(可进行其他操作)——>继续操作
根据是否能得到及时的应答,若需要等待的是阻塞,否则为非阻塞。

3 线程优先级

      RT-Thread 最大支持 256 个线程优先级 (0~255),数值越小的优先级越高,0 为最高优先级。在一些资源比较紧张的系统中,可以根据实际情况选择只支持 8 个或 32 个优先级的系统配置;对于 ARM Cortex-M系列,普遍采用 32 个优先级。最低优先级默认分配给空闲线程使用,用户一般不使用。在系统中,当有比当前线程优先级更高的线程就绪时,当前线程将立刻被换出,高优先级线程抢占处理器运行。

4 时间片

    每个线程都有时间片这个参数,但时间片仅对优先级相同的就绪态线程有效。

注:作为一个实时系统,一个优先级明确的实时系统,如果一个线程中的程序陷入了死循环操作,那么比它优先级低的线程都将不能够得到执行。所以在实时操作系统中必须注意的一点就是:线程中不能陷入死循环操作,必须要有让出 CPU使用权的动作,如循环中调用延时函数或者主动挂起。

2.3线程之间的切换

注:就绪状态运行状态是等同的

2.4系统线程

RT-Thread 内核中的系统线程有空闲线程和主线程。

3 线程相关操作

        线程相关的操作包括:创建/初始化、启动、运行、删除/脱离。

         动态线程与静态线程的区别是:动态线程是系统自动从动态内存堆上分配栈空间与线程句柄(初始化 heap 之后才能使用 create 创建动态线程),静态线程是由用户分配栈空间与线程句柄。

 3.1 创建和删除线程(动态创建删除线程)

说明:

*
 * @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 stack_size,
                             rt_uint8_t  priority,
                             rt_uint32_t tick)


/**
 * This function will delete a thread. The thread object will be removed from
 * thread queue and deleted from system object management in the idle thread.
 *
 * @param thread the thread to be deleted
 *
 * @return the operation status, RT_EOK on OK, -RT_ERROR on error
 */
rt_err_t rt_thread_delete(rt_thread_t thread)

 3.2、初始化和脱离线程(静态创建删除线程)

     线程的初始化可以使用下面的函数接口完成,来初始化静态线程对象:

/**
 * This function will initialize a thread, normally it's used to initialize a
 * static thread object.
 *
 * @param thread the static thread object
 * @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_start the start address of thread stack
 * @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 operation status, RT_EOK on OK, -RT_ERROR on error
 */
rt_err_t rt_thread_init(struct rt_thread *thread,
                        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)

/**
 * This function will detach a thread. The thread object will be removed from
 * thread queue and detached/deleted from system object management.
 *
 * @param thread the thread to be deleted
 *
 * @return the operation status, RT_EOK on OK, -RT_ERROR on error
 */
rt_err_t rt_thread_detach(rt_thread_t thread)

3.3 启动线程

/**
 * This function will start a thread and put it to system ready queue
 *
 * @param thread the thread to be started
 *
 * @return the operation status, RT_EOK on OK, -RT_ERROR on error
 */
rt_err_t rt_thread_startup(rt_thread_t thread)

注:当调用这个函数时,将线程的状态更改为就绪状态,并放到相应优先级队列中等待调度。如果新启动的线程优先级比当前线程优先级高,将立刻切换到这个线程。

3.4 获得当前线程

       在程序的运行过程中,相同的一段代码可能会被多个线程执行,在执行的时候可以通过下面的函数接口获得当前执行的线程句柄

/**
* This function will return self thread object
 *
 * @return the self thread object , failed RT_NULL
 */
rt_thread_t rt_thread_self(void)

3.5、让出处理器资源 

/**
 * This function will let current thread yield processor, and scheduler will
 * choose a highest(բ/ָĊ׮ߓŏȼ) thread to run. After yield processor, the current thread
 * is still in READY state.
 *
 * @return RT_EOK
 */
rt_err_t rt_thread_yield(void)

3.6 线程睡眠 

/**
 * This function will let current thread sleep for some ticks.
 *
 * @param tick the sleep ticks
 *
 * @return RT_EOK
 */
rt_err_t rt_thread_sleep(rt_tick_t tick)
rt_err_t rt_thread_delay(rt_tick_t tick)


/**
 * This function will let current thread delay for some milliseconds.
 *
 * @param tick the delay time
 *
 * @return RT_EOK
 */
rt_err_t rt_thread_mdelay(rt_int32_t ms)

注: rt_int32_t ms = 1/RT_TICK_PER_SECOND

3.7 控制线程函数

/**
 * This function will control thread behaviors according to control command.
 *
 * @param thread the specified thread to be controlled
 * @param cmd the control command, which includes
 *  RT_THREAD_CTRL_CHANGE_PRIORITY for changing priority level of thread;
 *  RT_THREAD_CTRL_STARTUP for starting a thread;  ==  rt_thread_startup()
 *  RT_THREAD_CTRL_CLOSE for delete a thread;      ==  rt_thread_delete()
 *  RT_THREAD_CTRL_BIND_CPU for bind the thread to a CPU.
 * @param arg the argument of control command
 *
 * @return RT_EOK
 */
rt_err_t rt_thread_control(rt_thread_t thread, int cmd, void *arg)

3.8 设置和删除idle线程hook函数 

/**
 * @ingroup Hook
 * This function sets a hook function to idle thread loop. When the system performs
 * idle loop, this hook function should be invoked.
 *
 * @param hook the specified hook function
 *
 * @return RT_EOK: set OK
 *         -RT_EFULL: hook list is full
 *
 * @note the hook function must be simple and never be blocked or suspend.
 */
rt_err_t rt_thread_idle_sethook(void (*hook)(void))

/**
 * delete the idle hook on hook list
 *
 * @param hook the specified hook function
 *
 * @return RT_EOK: delete OK
*         -RT_ENOSYS: hook was not found
 */
rt_err_t rt_thread_idle_delhook(void (*hook)(void))

注意:空闲线程是一个线程状态永远为就绪态线程,因此设置的钩子函数必须保证空闲线程在任何时刻都不会处于挂起状态,例如 rt_thread_delay()rt_sem_take() 等可能会导致线程挂起的函数都不能使用。

 3.9、设置调度器hook函数

       在整个系统的运行时,系统都处于线程运行、中断触发 - 响应中断、切换到其他线程,甚至是线程间的切换过程中,或者说系统的上下文切换是系统中最普遍的事件。有时用户可能会想知道在一个时刻发生了什么样的线程切换,可以通过调用下面的函数接口设置一个相应的钩子函数。在系统线程切换时,这个钩子函数将被调用。

/**
 * This function will set a hook function, which will be invoked when thread
 * switch happens.
 *
 * @param hook the hook function
 */
void rt_scheduler_sethook(void (*hook)(struct rt_thread *from, struct rt_thread *to))

struct rt_thread *from(从), struct rt_thread *to(到)

void hook(struct rt_thread *from, struct rt_thread *to)
{
     rt_kprintf("form %s to %s\n",from->name,to->name);
}
rt_scheduler_sethook(hook);

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值