[RTT例程练习] 1.3 线程让出

本文探讨了RTT(RT-Thread)实时操作系统中线程如何让出执行权,强调了与ucosii的不同,即RTT支持相同优先级线程的并发。在RTT中,即使不调用rt-thread_delay(),线程也会因为时间片机制自动让出调度器,保证了系统的公平性。通过具体实例展示了如何实现线程的主动让出。
摘要由CSDN通过智能技术生成

RTT 支持相同优先级,而ucosii 不支持。

如果一个线程不调用rt-thread_delay() 来让出调度器,那么它就会一直运行,其它线程永远处于就绪态。

而相同优先级的线程,在初始化或创建时还定义了其单次运行的最长的时间片,强迫其让出调度器。


这里,使用rt_thread_yield(); 也可让出调度器。

#include <rtthread.h>

rt_thread_t tid1 = RT_NULL;
rt_thread_t tid2 = RT_NULL;

static void thread1_entry(void* parameter)
{
    rt_uint32_t count = 0;
    
    while (1)
    {
        rt_kprintf(" thread1: count = %d\n", count++);

        rt_thread_yield();
    }   
}

static void thread2_entry(void* parameter)
{
    rt_uint32_t count = 0;

    while (1)
    {
        rt_thread_yield();

        rt_kprintf(" thread2: count = %d\n", count++);
    }
}



/* 两者的优先级必须相同,否则一个线程让出调度器之后进入就绪队列, 
   其优先级仍比另一个高,会继续执行,使得另一个线程始终无法得到
   运行。 */
int rt_application_init()
{
    tid1 = rt_thread_create("t1", 
        thread1_entry,
        RT_NULL,
        512,
        6, 10);
    if (tid1 != RT_NULL)
        rt_thread_startup(tid1);

    tid2 = rt_thread_create("t2", 
        thread2_entry,
        RT_NULL,
        512,
        6, 10);
    if (tid2 != RT_NULL)
        rt_thread_startup(tid2);

    return 0;
}   

/*@}*/


输出结果为:

\ | /
- RT - Thread Operating System
/ | \ 1.1.0 build Aug 10 2012
2006 - 2012 Copyright by rt-thread team
thread1: count = 0
thread1: count = 1
thread2: count = 0
thread1: count = 2
thread2: count = 1
thread1: count = 3
thread2: count = 2
thread1: count = 4
thread2: count = 3
thread2: count = 4



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值