RT_Thread 线程时间片轮转

本文介绍了一个使用时间片轮转调度策略的简单线程管理示例。通过创建两个具有不同时间片的线程(thread1和thread2),演示了在操作系统调度下线程如何按时间片交替运行直至完成指定任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建两个线程,堆和优先级相同,线程1 时间片为10 、线程2时间片为5。

注意: 时间片轮转机制,在 OS Tick 到来时,正在运行的线程时间片减 1

由于在线程时间片 到来的最后一个OS Tick 时刻,会由操作系统调度进行线程的切换操作。

创建线程 thread1 和 thread2,优先级相同为 20, thread1 时间片为 10, thread2
时间片为 5;
(2)启动线程 thread1 和 thread2,使 thread1 和 thread2 处于就绪状态;
(3)在操作系统的调度下, thread1 首先被投入运行;
(4) thread1 循环打印带有累计计数的信息,当 thread1 运行到第 10 个时间片时,操作系统调度
thread2 投入运行, thread1 进入就绪状态;
(5) thread2 开始运行后,循环打印带有累计计数的信息,直到第 15 个 OS Tick 到来, thread2 已经
运行了 5 个时间片,操作系统调度 thread1 投入运行, thread2 进入就绪状态;
(6) thread1 运行直到计数值 count>200,线程 thread1 退出,接着调度 thread2 运行直到计数值
count>200, thread2 线程退出;之后操作统调度空闲线程投入运行

#define THREAD_STACK_SIZE	1024
#define THREAD_PRIORITY	    20
#define THREAD_TIMESLICE    10

/* 线程入口 */
static void thread_entry(void* parameter)
{
    rt_uint32_t value;
    rt_uint32_t count = 0;

    value = (rt_uint32_t)parameter;
    while (1)
    {
        if(0 == (count % 5))
        {           
            rt_kprintf("thread %d is running ,thread %d count = %d\n", value , value , count);      

            if(count > 200)
                return;            
        }
         count++;
     }  
}

int timeslice_sample(void)
{
    rt_thread_t tid;
    /* 创建线程1 */
    tid = rt_thread_create("thread1", 
                            thread_entry, (void*)1, 
                            THREAD_STACK_SIZE, 
                            THREAD_PRIORITY, THREAD_TIMESLICE); 
    if (tid != RT_NULL) 
        rt_thread_startup(tid);


    /* 创建线程2 */
    tid = rt_thread_create("thread2", 
                            thread_entry, (void*)2,
                            THREAD_STACK_SIZE, 
                            THREAD_PRIORITY, THREAD_TIMESLICE-5);
    if (tid != RT_NULL) 
        rt_thread_startup(tid);
    return 0;
}

/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(timeslice_sample, timeslice sample);

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值