轮询调度
优先级和时间片是线程的两个重要参数,分别描述了线程竞争处理器资源的能力和持有处理器时间的能力
-
优先级
RT-Thread最大支持256个优先级(数值越小优先级越高,0为最高优先级,最低优先级预留给空闲线程);
用户可以通过rt_config.h中的RT_THREAD_PRIORITY_MAX宏来修改最大支持的优先级;
对于STM32默认设置最大支持32个优先级;
具体应用中,线程总数不受限制,能创建的线程总数只和具体硬件平台的内存有关; -
时间片
时间片只在处在就绪态的线程当中优先级相同的线程之间起作用,优先级相同的就绪态线程,由于优先级相同无法通过优先级高低来抢占资源,这时通过各自线程的时间片来轮换占用系统资源,时间片起到了约束线程单次运行时长的作用,其单位是一个系统节拍(OS Tick);
官方示例代码:
/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018-08-24 yangjie the first version
*/
/*
* 程序清单:相同优先级线程按照时间片轮番调度
*
* 这个例子中将创建两个线程,每一个线程都在打印信息
*
*/
#include <rtthread.h>
#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);