首页 > 技术文章 > RT-Thread 线程调度

yygsj 2016-05-17 09:32 原文

/*  变量分配4字节对齐 */
ALIGN(RT_ALIGN_SIZE)

/*  静态线程的 线程堆栈*/
static rt_uint8_t thread1_stack[512];
static rt_uint8_t thread2_stack[512];

/* 静态线程的 线程控制块 */
static struct rt_thread thread_test1;
static struct rt_thread thread_test2;


static void test1_thread_entry(void* parameter);
static void test2_thread_entry(void* parameter);

void demo_thread_creat(void)
{
    rt_err_t result;

    /* 创建静态线程 : 优先级 15 ,时间片 10个系统滴答 */
    result = rt_thread_init(&thread_test1,
                                  "test1",
                       test1_thread_entry, 
                                  RT_NULL,
           (rt_uint8_t*)&thread1_stack[0], 
                       sizeof(thread1_stack), 
                                       15, 
                                       10);
    if (result == RT_EOK)
    {
        rt_thread_startup(&thread_test1);
    }

    /* 创建静态线程 : 优先级 16 ,时间片 25个系统滴答 */
    result = rt_thread_init(&thread_test2,
                                  "test2",
                       test2_thread_entry, 
                                  RT_NULL,
           (rt_uint8_t*)&thread2_stack[0], 
                    sizeof(thread2_stack),
                                       16,
                                      25);
    if (result == RT_EOK)
    {
        rt_thread_startup(&thread_test2);
    }

}

void test1_thread_entry(void* parameter)
{

    rt_uint32_t i;
    /* 无限循环*/
    while (1)
    {
        for(i = 0; i<10; i++)
        {
            rt_kprintf(" %d \r\n", i);
            /* 等待1s,让出cpu权限,切换到其他线程 */
            rt_thread_delay( 100 );

        }
    }
}

void test2_thread_entry(void* parameter)
{
    rt_uint32_t i=0;
    /* 无限循环*/
    while (1)
    {
        rt_kprintf(" test2 thread count:%d \r\n", ++i);
        /* 等待0.5s,让出cpu权限,切换到其他线程 */
        rt_thread_delay(50);
    }
}

程序运行分析:
1、首先系统调度 test1 线程投入运行,打印第 0 次运行的信息,然后通过延时函数将自己挂起 100 个时间片,系统将 test2 线程调度运行;
2、 test2 线程打印第 0 次运行信息,然后通过延时函数将自己挂起 50 个时间片;
3、系统中无任务运行,系统将空闲线程调入运行;
4、 50 个时间片后 test2 线程被唤醒,打印第 1 次运行的信息,再继续通过延时函数将自己挂起 50 个时间片;
5、系统中无任务运行,系统将空闲线程调入运行;
6、 50 个时间片时间到, test1 线程被唤醒,打印第 1 次运行信息,继续挂起 100 个时间片;
7、 test2 线程被唤醒,打印第 2 次运行的信息,再继续通过延时函数将自己挂起 50 个时间片;
8、系统中无任务运行,系统将空闲线程调入运行;
9、 50 个时间片后 test2 线程被唤醒,打印第 3 次运行的信息,再继续通过延时函数将自己挂起 50 个时间片;
10、循环执行 5-9 的过程。

 

为了演示 test1 线程、 test2 线程之间的切换,我们需在程序中屏蔽掉 finsh 组件( finsh组件会建立 shell 线程):
/* SECTION: finsh, a C-Express shell */
//#define RT_USING_FINSH

 

RT-Thread的shell系统——finsh,提供了一套供用户在命令行操作的接口,主要用于调试、查看系统信息。 finsh被设计成一个不同于传统命令行的C语言表达式解释器:由于很多嵌入式系统都是采用C语言来编写, finsh正是采用了这种系统软件开发人员都会的语法形式,把C语言表达式变成了命令行的风格。它能够解析执行大部分C语言的表达式,也能够使用类似于C语言的函数调用方式访问系统中的函数及全局变量,此外它也能够通过命令行方式创建变量。

 

推荐阅读