一、临界资源
临界区资源是指一次仅允许一次线程的访问的共享资源。它可以是一个具体的硬件设备,也可以是一个变量、一个缓冲区。
不论是硬件临界资源,还是软件临界资源,多个线程必须互斥地对他们进行访问。
临界区
每个线程中访问(操作)临界区资源的那段代码称为临界区(Critical Section), 我们每次只允许一个线程进入临界区。
二、关闭系统调度
1.禁止调度
禁止调度,既是把调度器锁住,不让其他进行线程切换。这样就能保证当前能保证当前运行的任务不被换出,直到调度器解锁,所以禁止调度是常用的临界区保护方法。
2.关闭中断
因为所有的线程的调度都是建立在中断的基础上的,所以,当我们关闭中断后,系统将不能再进行调度,线程自身也自然不会被其他线程抢占了。
三、临界区保护实例
线程代码:
/*
* 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 <rthw.h>
#include <rtthread.h>
#define THREAD_PRIORITY 20
#define THREAD_STACK_SIZE 512
#define THREAD_TIMESLICE 5
/* 同时访问的全局变量 */
static rt_uint32_t cnt;
void thread_entry(void *parameter)
{
rt_uint32_t no;
rt_uint32_t level;
no = (rt_uint32_t) parameter;
while (1)
{
/* 关闭中断 */
level = rt_hw_interrupt_disable();
cnt += no;
/* 恢复中断 */
rt_hw_interrupt_enable(level);
rt_kprintf("protect thread[%d]'s counter is %d\n", no, cnt);
rt_thread_mdelay(no * 10);
}
}
/* 用户应用程序入口 */
int interrupt_sample(void)
{
rt_thread_t thread;
/* 创建t1线程 */
thread = rt_thread_create("thread1", thread_entry, (void *)10,
THREAD_STACK_SIZE,
THREAD_PRIORITY, THREAD_TIMESLICE);
if (thread != RT_NULL)
rt_thread_startup(thread);
/* 创建t2线程 */
thread = rt_thread_create("thread2", thread_entry, (void *)20,
THREAD_STACK_SIZE,
THREAD_PRIORITY, THREAD_TIMESLICE);
if (thread != RT_NULL)
rt_thread_startup(thread);
return 0;
}
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(interrupt_sample, interrupt sample);
注意:在关闭中断的过程中,是不会被其他线程抢去的,所以在关闭中断中,只会有这一段代码进行编译;如果,我们不恢复中断设置的话,会出现线程死锁的状态,不会跳出此线程;