当前位置:网站首页>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访问共享状态。
边栏推荐
- 转换Cifar10数据集
- Most commonly used SQL statements
- Finally, we can figure out whether the binding event in the tag is bracketed or not
- 不要小看了积分商城,它的作用可以很大!
- 李飞飞团队将ViT用在机器人身上,规划推理最高提速512倍,还cue了何恺明的MAE
- Interviewer: your resume says you are proficient in mysql, so you say cluster / Union / overlay index, table return, index push down
- Don't underestimate the integral mall, its role can be great!
- How to reload the win10 app store?
- Download and installation tutorial of consumer
- Sleep formula: how to cure bad sleep?
猜你喜欢

04. binary tree

解析数仓lazyagg查询重写优化

Do you want to go to an outsourcing company? This article will give you a comprehensive understanding of outsourcing pits!

Asynchronous processing of error prone points

Binocular 3D perception (I): preliminary understanding of binocular

教务系统开发(PHP+MySQL)

The release of autok3s v0.5.0 continues to be simple and friendly
Why does golang's modification of slice data affect the data of other slices?

Don't underestimate the integral mall, its role can be great!

Rapport de la main - d'oeuvre du Conseil de développement de l'aecg air32f103cbt6
随机推荐
Mt60b1g16hc-48b:a micron memory particles FBGA code d8bnk[easy to understand]
揭秘GaussDB(for Redis):全面对比Codis
MySQL modifier l'instruction de champ
What is the NFT digital collection?
Converting cifar10 datasets
有哪些新手程序员不知道的小技巧?
Source code analysis of nine routing strategies for distributed task scheduling platform XXL job
Go development team technical leader Russ Cox sends a document to share go's version control history
Client development (electron) system level API usage 2
Tensorflow loading cifar10 dataset
Free books! AI across the Internet paints old photos. Here is a detailed tutorial!
将一个文件写入到另一个文件的标记位置
What is OA
Analysis of the concept of metacosmic system
How to reload the win10 app store?
GridLayout evenly allocate space
Understand the execution sequence of try catch finally in one diagram
Write one file to the marked location of another file
Create raspberry PI image file of raspberry pie
Pytest test framework notes