当前位置:网站首页>Go language - lock operation
Go language - lock operation
2022-06-25 16:03:00 【Crying while learning】
summary
sync Package document :Package sync - The Go Programming Language
sync Packages provide basic synchronization operations , Such as mutual exclusion lock . except Once and WaitGroup outside , Most types are used by low-level library routines . The more advanced synchronization is better through channel And communication .
The mutex Mutex
Mutexes are more violent , When one goroutine After obtaining the mutex , Other goroutine You can only wait for the lock to be released .
When using mutex , You must unlock the resource after the operation , Otherwise the program will deadlock . It is recommended to use defer Statement to unlock .
// Define mutex objects
var mutex_name sync.Mutex
// locked
mutex_name.Lock()
// Unlock
mutex_name.Unlock()The same is the problem of ticket sales at the railway station , Let's take a look at the effect of solving the critical resource problem through mutual exclusion
// Ticket allowance
var tickets = 5
// Define synchronization waiting groups
var wg sync.WaitGroup
// Define mutex objects
var mutex sync.Mutex
func main() {
wg.Add(3)
go saleTickets("1 Ticket booth No ")
go saleTickets("2 Ticket booth No ")
go saleTickets("3 Ticket booth No ")
wg.Wait()
}
func saleTickets(name string) {
for {
mutex.Lock()
if tickets > 0 {
fmt.Printf(" Ticket remaining :%v, %v Sell out \n", tickets, name)
tickets--
time.Sleep(1 * time.Second)
} else {
mutex.Unlock()
fmt.Println(" The tickets have been sold out ...")
wg.Done()
break
}
mutex.Unlock()
}
}
Read-write lock RWMutex
The difference between a read-write lock and an ordinary mutex lock is , It is a kind of mutex for read and write operations .
Multiple read operations are allowed at the same time , But only one write operation is allowed at a time . And during a write operation , Read operations are also not allowed . So , Read / write locks can be concurrent for read operations , But for write operations, they are completely mutually exclusive .
// Define the read / write lock object
var rwmutex_name sync.RWMutex
// Read the lock
rwmutex_name.RLock
// Read unlock
rwmutex_name.RUnlock
// Write lock
rwmutex_name.Lock
// Write unlock
rwmutex_name.UnlockWe will not show the example of read-write lock , Because the effect should not be different from the example shown above .
The problem actually solved with write locks is , The use of mutexes reduces concurrency . Because mutexes block both read and write operations , The program has changed from concurrent to serial .
In fact, for read operations that do not modify critical resources , We don't need to block ; Only write operations that need to be modified for critical resources , We just need to block . So read-write locking is to improve the concurrency of programs when locking .
边栏推荐
- SQL最常用的语句
- Yadali brick playing game based on deep Q-learning
- B站付费视频使up主掉粉过万
- Sword finger offer 05 Replace spaces
- [issue 24] one year experience of golang to develop futu
- Pytest test framework notes
- Lifeifei's team applied vit to the robot, increased the maximum speed of planning reasoning by 512 times, and also cued hekaiming's MAE
- Why is it said that restarting can solve 90% of the problems
- Rapport de la main - d'oeuvre du Conseil de développement de l'aecg air32f103cbt6
- Native JS dynamically add elements
猜你喜欢

李飞飞团队将ViT用在机器人身上,规划推理最高提速512倍,还cue了何恺明的MAE
Introduction to database transactions

Resolve Visio and office365 installation compatibility issues

《睡眠公式》:怎么治睡不好?
Desktop development (Tauri) opens the first chapter

Asynchronous processing of error prone points

Interviewer: your resume says you are proficient in mysql, so you say cluster / Union / overlay index, table return, index push down

Sword finger offer 04 Find in 2D array
After the project is pushed to the remote warehouse, Baota webhook automatically publishes it

Do you want to go to an outsourcing company? This article will give you a comprehensive understanding of outsourcing pits!
随机推荐
[golang] leetcode intermediate - find the first and last position of an element in a sorted array & Merge interval
Message format of Modbus (PLC)
What can NFT metauniverse development do?
Take you to the open source project of smart home: the preliminary configuration of zhiting home cloud and home assistant+ homebridge
What is OA
TFIDF与BM25
Open the box to experience rust, come on!!!
How to debug grpc by postman
合宙Air32F103CBT6開發板上手報告
How to reload the win10 app store?
Lecun predicts AgI: big model and reinforcement learning are both ramps! My "world model" is the new way
Time wheel and implementation analysis of time wheel in go zero
元宇宙系统的概念解析
MySQL installation tutorial
面试官:你简历上说精通mysql,那你说下聚簇/联合/覆盖索引、回表、索引下推
QC, QA, IPQC, JQE, DQA, SQE, DQC, MQC, IQC, FQC, OQC
Rapport de la main - d'oeuvre du Conseil de développement de l'aecg air32f103cbt6
数据类型的内置方法
Tensorflow loading cifar10 dataset
Analysis of the concept of metacosmic system