静态线程的栈是在编译时确定的,故不能由内核动态的创建或删除。静态线程只能通过detach 来使其脱离内核的调度而做不到 delete。
所以静态线程中会像这样定义栈
static rt_uint8_t thread1_stack[512];
这一点是和ucosii 类似的,但ucosii 没有动态线程。
个人感觉动态线程更有优势,也更像PC。尤其是在外扩了SRAM的情况下优势就更明显了。
原官网有比较全的解释:
总结
什么是动态线程?什么是静态线程?两者有什么区别?
RT-Thread中支持静态和动态两种定义方式。用线程来举例的话,rt_thread_init对应静态定义方式, rt_thread_create 对应动态定义方式。
使用静态定义方式时,必须先定义静态的线程控制块,并且定义好堆栈空间,然后调用rt_thread_init来完成线程的初始化工作。采用这种方式,线程控制块和堆栈占用的内存会放在RW段,这段内存空间在编译时就已经确定,它不是可以动态分配的,所以不能被释放,而只能使用 rt_thread_detach 函数将该线程控制块从对象管理器中脱离。
使用动态定义方式 rt_thread_create 时, RT-Thread 会动态申请线程控制块和堆栈空间。当不需要使用该线程时,调用rt_thread_delete函数就会将这段申请的内存空间重新释放到内存堆中(如果线程执行完毕,退出时,系统也会自动回收线程控制块和堆栈空间)
代码就很简单了,类似于实验1.1 , 一个线程让另一个线程脱离调度器调度。
#include <rtthread.h>
static struct rt_thread thread1;
static struct rt_thread thread2;
static rt_uint8_t thread1_stack[512];
static rt_uint8_t thread2_stack[512];
/* entry for thread1 */
static void thread1_entry(void* parameter)
{
rt_uint32_t count = 0;
while(1)
{
rt_kprintf("thread count: %d\n", count++);
rt_thread_delay(RT_TICK_PER_SECOND);
}
}
static void thread2_entry(void* parameter)
{
rt_thread_delay(RT_TICK_PER_SECOND * 10);
rt_thread_detach(&thread1);
rt_thread_delay(10);
}
int rt_application_init()
{
rt_err_t result;
result = rt_thread_init(&thread1, "t1",
thread1_entry, RT_NULL,
&thread1_stack[0], sizeof(thread1_stack),
7, 10);
if (result == RT_EOK)
rt_thread_startup(&thread1);
result = rt_thread_init(&thread2, "t2",
thread2_entry, RT_NULL,
&thread2_stack[0], sizeof(thread2_stack),
6, 10);
if (result == RT_EOK)
rt_thread_startup(&thread2);
return 0;
}
输出结果:
\ | /
- RT - Thread Operating System
/ | \ 1.1.0 build Aug 10 2012
2006 - 2012 Copyright by rt-thread team
thread count: 0
thread count: 1
thread count: 2
thread count: 3
thread count: 4
thread count: 5
thread count: 6
thread count: 7
thread count: 8
thread count: 9