当前位置:网站首页>如何在不加锁的情况下解决线程安全问题
如何在不加锁的情况下解决线程安全问题
2022-04-21 19:55:00 【皇家大少つ】
1. 什么是线程安全问题
线程安全问题就是多个线程同时对于某个共享资源的访问,导致的原子性,可见性和有序性的问题,而这些问题会导致共享数据存在一个不可预测性,使得程序在执行过程中会出现一些超过预期的一个结果


2. 解决线程安全问题的方式
一般情况下解决线程安全问题的方式是增加同步锁,常见的是像synchronzied,lock等等,由于导致线程安全问题的根本原因是多线程并行访问。对共享资源加锁之后呢,多个线程在访问这个资源的时候,必须要先获得锁,也就是先获得访问资格,而同步锁的特征是在同一个时刻只允许一个线程访问这样一个资源,直到锁被释放,虽然这种方式,可以解决线程安全性的一个问题,但同时带来的是加锁和释放锁所带来的一个性能开销,因为加锁涉及用户空间和内核空间的一个转换以及上下文切换
3. 如何在不加锁解决线程安全问题
如何在性能和安全性之间去取得一个平衡,这就引出了一个无锁并发的概念,一般来说会有以下几种说法
- 通过自选锁(CAS),所谓自选锁是指线程在没有抢占的锁的情况下先自旋指定的次数,去尝试获得锁

- 乐观锁,给每个数据增加一个版本号,一旦数据发生变化,则去修改这个版本号,那在Java里面,有一个CAS的一个机制,去完成乐观锁的一个功能
- 在程序设计中,尽量去减少共享对象的一个使用,从业务上去实现隔离避免并发
版权声明
本文为[皇家大少つ]所创,转载请带上原文链接,感谢
https://blog.csdn.net/ahuangqingfeng/article/details/124328333
边栏推荐
- Enterprise cross-border e-commerce platform service solution, cross-border e-commerce trade business framework construction, operation and maintenance
- R语言数据分析从入门到高级:(八)数据清洗技巧之数据格式转换(包含宽数据与长数据之间的转换)
- High end manufacturing enterprise informatization solution, predictive maintenance of industrial e-commerce platform equipment, data and system
- Publicity of the winners of the 9th "Datang Cup" National College Students' mobile communication 5g technology competition
- PostgreSql 连接访问控制
- 824. Goat Latin
- 有趣的灵魂千篇一律,电脑滑动关机,仅需2步
- SAP PS 第12节 网络成本计划
- leetcode18. Sum of four numbers
- SAP MTS / MTO / ETO topic 7: front and rear operation in Q + M mode
猜你喜欢
![[线性代数]向量究竟是什么?](/img/71/1c34808b67a12cf8b402c846293f4f.png)
[线性代数]向量究竟是什么?

Modifying the root password of MySQL

Imea | endnote tutorial on adjusting perfect citation format (video)

Xinguan is merciless, human beings have feelings, Xinlong agriculture ensures people's livelihood and jointly fights the epidemic -- condolences to the front line of fighting the epidemic, love the el

SAP MTS / MTO / ETO topic 7: front and rear operation in Q + M mode

R语言数据分析从入门到高级:(八)数据清洗技巧之数据格式转换(包含宽数据与长数据之间的转换)

Solutions informatiques pour les entreprises manufacturières haut de gamme, maintenance prédictive de l'équipement, des données et du système de la plate - forme de commerce électronique industriel

Interesting souls are the same. It takes only 2 steps to slide the computer off
![LeetCode 山羊拉丁文[模拟 字符串] HERODING的LeetCode之路](/img/da/3761b46aec6a56f2f30e0fd91c7f42.png)
LeetCode 山羊拉丁文[模拟 字符串] HERODING的LeetCode之路
![[timing] lstnet: a time series prediction model combining CNN, RNN and ar](/img/b7/5b4fb5fc36f72aabfb04eafb941b57.png)
[timing] lstnet: a time series prediction model combining CNN, RNN and ar
随机推荐
数商云:剖析企业采购管理的现状,推进企业采购模式优化升级
多因子策略
SAP PS section 12 network cost plan
leetcode18. Sum of four numbers
杰理之使用不可屏蔽中断的开关中断函数【篇】
2022下半年PMP考试开始报名,须知
Considerations for index creation
小程序项目文件介绍
图像中stride的含义
PE市盈率们之间的区别
SAP MTS / MTO / ETO topic 7: front and rear operation in Q + M mode
Building / building reusable QML modules using cmake
【2021】腾讯秋招技术岗编程 有效序列的数量
界面组件Telerik UI for WPF入门指南 - 颜色主题生成器
redis
824. Goat Latin
auto 关键字的使用
[线性代数]向量究竟是什么?
flinkx部署
码出高效 第七章 并发与多线程