Zephyr内核 之 Threads

  • Thread

A thread is a kernel object that is used for application processing that is too lengthy or too complex to be performed by an ISR.

  • thread is referenced by a thread id

Each thread is referenced by a thread id that is assigned when the thread is spawned.

Lifecycle

Thread Creation(线程创建)

  • 先创建,后使用
  • 可立即或延迟启动
  • 延迟启动可启动前取消,但需重新生成

Thread Termination(线程终止)

  • 通过从入口点函数返回,同步结束线程的运行
  • 终止的线程负责释放其拥有的任何共享资源(如互斥锁、动态分配的内存)
  • 使用k_thread_abort() 和 k_thread_join() 同步线程终止状态
    • k_thread_abort() 中止目标线程
    • k_thread_join() 休眠直到目标线程退出

Thread Aborting(线程中止)

  • 其他线程(包括自身)终止 或 线程触发错误导致内核自动退出该线程
  • 最好用信号通知线程优雅地自终止

Thread Suspension(线程挂起)

  • k_thread_suspend() 挂起目标线程,k_thread_resume() 恢复目标线程

Thread States

ready: 没有阻碍进程执行的因素,符合条件被调度器选为当前进程;
unready:有一个或多个阻碍进程执行的因素,不能被调度器选为当前进程;

  • Note
    Although the diagram above may appear to suggest that both Ready and Running are distinct thread states, that is not the correct interpretation. Ready is a thread state, and Running is a schedule state that only applies to Ready threads.

Thread Stack objects(线程堆栈对象)

线程优先级

  • 值越小,优先级越高;
  • 优先级数据几乎无限制;

根据优先级分为两类线程:
协作线程:(- CONFIG_NUM_COOP_PRIORITIES) 到 -1
可抢占线程:0 到 ( CONFIG_NUM_PREEMPT_PRIORITIES- 1)

协作线程:不可抢占,成为当前线程后会一直保持,直到自身进入unready状态。
可抢占线程:随时可被抢占,成为当前线程,一旦优先级相同或更高的线程进入ready状态,即被抢占。

元中断优先级(Meta- IRQ priorities)

  • 是协作线程优先级的子类,占据优先级最高端区域;
  • 仍然是个线程,自有堆栈,而不是CPU的中断堆栈;
  • 谨慎使用,特别简单特别高优先级的线程才能考虑。

线程选项(Thread Options)

  • K_ESSENTIA
  • K_SSE_REGS
    x86架构使用SSE寄存器
  • K_FP_REGS
    使用CPU浮点寄存器
  • K_USER
    如果CONFIG_USERSPACE启用,此线程将在用户模式下创建,并降低权限。
  • K_INHERIT_PERMS
    继承父线程权限,用户模式使用

线程的使用

线程创建
方法1: k_thread_create(), 定义堆栈区域、线程控制块,使用

#define MY_STACK_SIZE 500
#define MY_PRIORITY 5

extern void my_entry_point(void *, void *, void *);

K_THREAD_STACK_DEFINE(my_stack_area, MY_STACK_SIZE);
struct k_thread my_thread_data;

k_tid_t my_tid = k_thread_create(&my_thread_data, my_stack_area,
                                 K_THREAD_STACK_SIZEOF(my_stack_area),
                                 my_entry_point,
                                 NULL, NULL, NULL,
                                 MY_PRIORITY, 0, K_NO_WAIT);

方法2: K_THREAD_DEFINE

#define MY_STACK_SIZE 500
#define MY_PRIORITY 5

extern void my_entry_point(void *, void *, void *);

K_THREAD_DEFINE(my_tid, MY_STACK_SIZE,
                my_entry_point, NULL, NULL, NULL,
                MY_PRIORITY, 0, 0);
posted @ 2022-05-22 21:42  宇哥来了  阅读(435)  评论(0编辑  收藏  举报