当前位置:网站首页>golang chan实现互斥锁
golang chan实现互斥锁
2022-07-27 15:53:00 【gitxuzan_】
// 使用chan实现互斥锁
type Mutex struct {
ch chan struct{
}
}
// 使用锁需要初始化
func NewMutex() *Mutex {
mu := &Mutex{
make(chan struct{
}, 1)}
mu.ch <- struct{
}{
}
return mu
}
// 请求锁,直到获取到
func (m *Mutex) Lock() {
<-m.ch
}
// 解锁
func (m *Mutex) Unlock() {
select {
case m.ch <- struct{
}{
}:
default:
panic("unlock of unlocked mutex")
}
}
// 尝试获取锁
func (m *Mutex) TryLock() bool {
select {
case <-m.ch:
return true
default:
}
return false
}
// 加入一个超时的设置
func (m *Mutex) LockTimeout(timeout time.Duration) bool {
timer := time.NewTimer(timeout)
select {
case <-m.ch:
timer.Stop()
return true
case <-timer.C:
}
return false
}
// 锁是否已被持有
func (m *Mutex) IsLocked() bool {
return len(m.ch) == 0
}
func main() {
m := NewMutex()
ok := m.TryLock()
fmt.Printf("locked v %v\n", ok)
ok = m.TryLock()
fmt.Printf("locked %v\n", ok)
}
边栏推荐
- [introduction to database system (Wang Shan)] Chapter 11 concurrency control
- Database hyperphone (4)
- Fast analysis combined with Haidian medicine
- Anaconda uninstall again
- PostgreSQL 14 支持winserver2022吗?
- 机器学习之评价指标(二)——分类评价指标
- 【obs】x264_ encoder_ Encode encoding output PTS DTS and framesize
- Taishan Office Technology Lecture: word strange paragraph borders
- Help, boost and take responsibility, the new value and significance of the 6th Tuba rabbit 718 national home decoration Festival
- In the first week of June, risk control of e-shield business paid attention to 15 institutions such as New Oriental XRS, which were fined
猜你喜欢

Oracle 11g database installation tutorial

ACL 2022 | prompt based automatic depolarization: effectively reducing bias in the pre training language model

美团到餐“祖传数仓”标准化治理笔记

Wechat applet realizes location map display and introduces map map without navigation

JSP自定义标签(下)
知物由学 | 小游戏的安全风险在哪里?

I got the P8 "top-level" distributed architecture manual crazy spread on Alibaba intranet

面试好难啊!蚂蚁金服的六轮面试我是强撑过来!差点OUT(面试复盘)

Convolutional neural network -- SSD thesis translation

机器学习之评价指标(二)——分类评价指标
随机推荐
卷积神经网络——SSD论文翻译
Layout of flutter
Wechat applet to make calls
【Codeforces】 B. Make it Divisible by 25
Some suggestions for writing original technical articles
运行loam_velodyne实时建图
What are the safety risks of small games?
Mysql database defines cursor in trigger
Convolutional neural network -- SSD thesis translation
Evaluation index of machine learning (I) -- regression evaluation index
知物由学 | 从0到1搭建实时反外挂机制,多维度补充手游攻防力
微信小程序 云函数批量删除多条数据 Error: errCode: -502005 database collection not exists
如何限制root远程登入,使普通用户拥有root权限
Knowing things by learning | app slimming down, the way of safety reinforcement under the new generation AAB framework
Operation of simulated examination platform for 2022 low voltage electrician examination questions
js实现右键菜单栏功能
Today's sleep quality record 82 points
Fast parsing combined with Huatu document encryption software
面试官:什么是脚手架?为什么需要脚手架?常用的脚手架有哪些?
[introduction to database system (Wang Shan)] Chapter 1 - Introduction