当前位置:网站首页>GO语言-什么是临界资源安全问题?
GO语言-什么是临界资源安全问题?
2022-06-25 15:39:00 【一边学习一边哭】
临界资源安全问题
临界资源:指并发编程中,可以被多个进程/线程/协程共同访问的资源。
如果在并发编程中对临界资源的处理不当,往往会导致数据不一致的问题。
火车站卖票问题demo,来演示临界资源安全问题
实现3个售票口同时售票
//车票余量
var tickets = 5
//定义同步等待组
var wg sync.WaitGroup
func main() {
wg.Add(3)
go saleTickets("1号售票口")
go saleTickets("2号售票口")
go saleTickets("3号售票口")
wg.Wait()
}
func saleTickets(name string) {
for {
if tickets > 0 {
fmt.Printf("车票剩余:%v, %v售出\n", tickets, name)
tickets--
} else {
fmt.Println("车票已售罄...")
wg.Done()
break
}
}
}
我们的参数一共设置了5张车票,但是程序最后反馈售出了7张车票。这就是临界资源的安全问题。
3个goroutine在某个时刻判断车票数量是否大于0的时候,这个时刻车票数量都是满足的。但是在执行接下来的售票操作时,其中一个goroutine的售票口先把票卖出去了,但是其他两个售票口已经通过了逻辑判断,也将票卖了出去。
如何解决临界资源安全问题?
1.大多数语言解决同步资源安全问题都是通过上锁的方式。某一时刻只能允许一个goroutine来访问这个共享数据。go语言中,可以借助sync包下的锁操作。
2.在go语言的并发编程中有一句经典的话:不要以共享内存的方式去通信,而要以通信的方式去共享内存。Go语言鼓励使用channel将共享状态或共享状态的变化在各个goroutine之间传递,这样就可以像锁一样保证同一时刻只有一个goroutine访问共享状态。
边栏推荐
- 解析数仓lazyagg查询重写优化
- How to debug grpc by postman
- Continuous integration of aspnetcore & cloud flow
- Yadali brick playing game based on deep Q-learning
- QC, QA, IPQC, JQE, DQA, SQE, DQC, MQC, IQC, FQC, OQC
- 基于神经标签搜索,中科院&微软亚研零样本多语言抽取式摘要入选ACL 2022
- golang使用mongo-driver操作——增(进阶)
- MySQL installation tutorial
- Sword finger offer 03 Duplicate number in array
- Source code analysis of nine routing strategies for distributed task scheduling platform XXL job
猜你喜欢

VectorDraw Developer Framework 10.1001 Crack

面试官:你简历上说精通mysql,那你说下聚簇/联合/覆盖索引、回表、索引下推

Startup and shutdown of appium service
Prototype mode

Uncover gaussdb (for redis): comprehensive comparison of CODIS
Why is it said that restarting can solve 90% of the problems
Take you to the open source project of smart home: the preliminary configuration of zhiting home cloud and home assistant+ homebridge

04. binary tree

Read the configuration, explain the principle and read the interview questions. I can only help you here...

LeCun预言AGI:大模型和强化学习都是斜道!我的「世界模型」才是新路
随机推荐
JS的注释
商城风格也可以很多变,DIY了解一下!
The paid video at station B caused the up master to lose more than ten thousand fans
JS add custom attributes to elements
Programmer vs hacker thinking | daily anecdotes
Write one file to the marked location of another file
Inter thread synchronization semaphore control
合宙Air32F103CBT6開發板上手報告
Vscode有什么好用的插件?
面试官:你简历上说精通mysql,那你说下聚簇/联合/覆盖索引、回表、索引下推
Popular cross domain
Do you want to go to an outsourcing company? This article will give you a comprehensive understanding of outsourcing pits!
Webgl and webgpu comparison [4] - uniform
Uncover gaussdb (for redis): comprehensive comparison of CODIS
MySQL修改字段語句
Pytest test framework notes
AspNetCore&云效Flow持续集成
LeCun预言AGI:大模型和强化学习都是斜道!我的「世界模型」才是新路
Differences between = = and = = = in JS (detailed explanation)
Multithreading, parallelism, concurrency, thread safety