当前位置:网站首页>【GoLang】同步锁 Mutex
【GoLang】同步锁 Mutex
2022-07-29 00:50:00 【JavaPub-rodert】
博主介绍: 自媒体 JavaPub 独立维护人,全网粉丝15w+,csdn博客专家、java领域优质创作者,51ctoTOP10博主,知乎/掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、
GoLang技术领域和副业。
同步锁
golang当中提供了两种常用的锁。
一种是 sync.Mutex (互斥锁) 另外一种是 sync.RWMutex (读写锁)
Mutex,它就是最简单最基础的同步锁,当一个goroutine持有锁的时候,其他的goroutine只能等待到锁释放之后才可以尝试持有。
RWMutex 是读写锁的意思,它支持一写多读,也就是说允许支持多个goroutine同时持有读锁,而只允许一个goroutine持有写锁。当有goroutine持有读锁的时候,会阻止写操作。当有goroutine持有写锁的时候,无论读写都会被堵塞。
案例
假设我们当前有多个goroutine,但是我们只希望持有锁的goroutine执行,我们可以这么写:
var lock sync.Mutex
for i := 0; i < 10; i++ {
go func() {
lock.Lock()
defer lock.Unlock()
// do something
}()
}
RWMutex区分了读写锁,所以我们一共会有4个api,分别是Lock, Unlock, RLock, RUnlock。Lock和Unlock是写锁的加锁以及解锁,而RLock和RUnlock自然就是读锁的加锁和解锁了。
面试题
Go 当中同步锁有什么特点?作用是什么?
- 阻塞。用于并发操作之间数据的安全保障。

边栏推荐
- [hcip] two mGRE networks are interconnected through OSPF (ENSP)
- Log4j dynamic loading configuration file
- How many of the top ten test tools in 2022 do you master
- [hcip] experiment of republishing and routing strategy
- DVWA之SQL注入
- RHCE command practice (II)
- New 1688 API access instructions
- Writing assignment 1
- PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益
- The solution to keep the height of the container unchanged during the scaling process of the uniapp movable view table
猜你喜欢

PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益

2022年最火的十大测试工具,你掌握了几个

采用QT进行OpenGL开发(二)绘制立方体

一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力

redis安装,集群部署与常见调优

DocuWare 移动劳动力解决方案可帮助您构建新的生产力模式:随时随地、任何设备

SQL question brushing: find the current salary details and department number Dept_ no

【HCIP】重发布及路由策略的实验

BOM系列之window对象

Platofarm community ecological gospel, users can get premium income with elephant swap
随机推荐
Subtotal of process thread coordination
Redis installation, cluster deployment and common tuning
Formal parameters, arguments, main function parameters, arrays or pointers as function parameters of the knowledge in every corner of C language
SQL question brushing: find the last of all employees who have been assigned departments_ Name and first_ Name and Dept_ no
代码生成器
els 到底停止
The new generation of public chain attacks the "Impossible Triangle"
Platofarm community ecological gospel, users can get premium income with elephant swap
JS judge whether array / object array 1 contains array / object array 2
OpenGL development with QT (II) drawing cube
uniapp createSelectorQuery(). Select get returns null error
New 1688 API access instructions
JS event introduction
BOM系列之window对象
【观察】三年跃居纯公有云SaaS第一,用友YonSuite的“飞轮效应”
RHCE command practice (II)
Analysis of Multi Chain use cases on moonbeam -- review of Derek's speech in Polkadot decoded 2022
J9 number theory: what factors determine the value of NFT?
RHCE command practice (I)
Openpyxl library fill color
