首页 > 技术文章 > RT-Thread 线程的让出

yygsj 2016-05-17 11:35 原文

前面两个例子演示的线程调度是由系统“主动干预”的情况的线程切换,其实我们也可以根据实际情况,采用主动让出 CPU 使用权。RT-Thread 中的系统函数: rt_thread_yield(),可以让调用它的线程暂时让出 CPU 的使用权,而使下一个最高优先级的线程得以运行,但这时调用 rt_thread_yield()的线程还保持的是就绪态。这和“孔融让梨”有点像:这个梨我不吃,下一个梨我可就不客气了。

#include <rtthread.h>
#include <stm32f10x.h>
#include "test.h"


/*  变量分配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 ,时间片 5个系统滴答 */
    result = rt_thread_init(&thread_test1,
                            "test1",
                            test1_thread_entry, RT_NULL,
                            (rt_uint8_t*)&thread1_stack[0], sizeof(thread1_stack), 15, 5);

    if (result == RT_EOK)
    {
        rt_thread_startup(&thread_test1);
    }

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

    if (result == RT_EOK)
    {
        rt_thread_startup(&thread_test2);
    }

}

void test1_thread_entry(void* parameter)
{
    rt_uint32_t count = 0;

    while (1)
    {
        /* 打印线程 1 的输出 */
        rt_kprintf("thread1: count = %d\n", count ++);

        /* 执行 yield 后应该切换到 test2 执行 */
        rt_thread_yield();
    }
}

void test2_thread_entry(void* parameter)
{
    rt_uint32_t count = 0;

    while (1)
    {
        /* 执行 yield 后应该切换到 test1 执行 */
        rt_thread_yield();

        /* 打印线程 2 的输出 */
        rt_kprintf("thread2: count = %d\n", count ++);
    }
}

 

推荐阅读