当前位置:网站首页>RT_thread 临界区保护
RT_thread 临界区保护
2022-07-13 17:50:00 【The endeavor】
一、临界资源
临界区资源是指一次仅允许一次线程的访问的共享资源。它可以是一个具体的硬件设备,也可以是一个变量、一个缓冲区。
不论是硬件临界资源,还是软件临界资源,多个线程必须互斥地对他们进行访问。
临界区
每个线程中访问(操作)临界区资源的那段代码称为临界区(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);

注意:在关闭中断的过程中,是不会被其他线程抢去的,所以在关闭中断中,只会有这一段代码进行编译;如果,我们不恢复中断设置的话,会出现线程死锁的状态,不会跳出此线程;
边栏推荐
猜你喜欢

Win10机器学习环境搭建—pycharm、anaconda、pytorch

KEIL中文乱码解决方法

【论文笔记】—VGG网络—2014-ICLR

【论文笔记】—毫米波雷达穿雾式高分辨率成像—Supervised—HawkEye系统—2020-CVPR

【論文筆記】—VGG網絡—2014-ICLR

基于RT_thread的分布式无线温度监控系统实战(一)

Catching both gray and black swans: open set supervised anomaly detection

Do you really understand JS event cycle

stride for plane for YUV
![[paper notes] - alexnet - 2012-acm](/img/67/9aa291229514004074350c1545146b.png)
[paper notes] - alexnet - 2012-acm
随机推荐
V4L2 操作流程和接口说明
【ICCV2021】Tokens-to-Token ViT: Training Vision Transformers From Scratch on ImageNet
【MIT Missing Semester 2】Shell Tools
论文阅读笔记——Crop yield prediction using deep neural networks
stride for plane for YUV
WKWebView之离线加载以及遇到的问题
[paper notes] - VGg Network - 2014-iclr
HDU 3666 THE MATRIX PROBLEM (差分约束+栈优化spfa判负环)
【ARXIV2203】Efficient Long-Range Attention Network for Image Super-resolution
【论文笔记】—AlexNet—2012-ACM
2021-07-19
Detailed explanation of HTTP caching mechanism
Wechat applet development two or three things
【论文笔记】—低照度图像增强—ZeroShot—RetinexDIP网络—2021-TCSVT
Cgrect, cgpoint, etc. cannot be added to the array problem
KEIL中文乱码解决方法
YYModel内部实现原理
防抖与节流:实践与勘误
Anti shake and throttling: practice and Corrigendum
【论文翻译】Issues and Challenges of Aspect-based Sentiment Analysis: A Comprehensive Survey