创建两个线程,堆和优先级相同,线程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);