其他
Mutex 和上厕所居然有这么多异曲同工之妙
The following article is from 薯条的编程修养 Author 程序员薯条
本文采取对话形式,有两个登场人物,左边是导师:欧阳狂霸,右边是实习生:三多。
提示:浅色主题阅读体验更佳。
Mutex介绍
欧阳狂霸小课堂
<<< 左右滑动见更多 >>>
func concurIncr() {
var wg sync.WaitGroup
wg.Add(10)
var a int
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
for j := 0; j < 1000; j++ {
a++
}
}()
}
wg.Wait()
println(a) // 小于10000的随机数。
}
欧阳狂霸小课堂
<<< 左右滑动见更多 >>>
CAS伪代码:
bool Cas(int32 *val, int32 old, int32 new)
Atomically:
if(*val == old){
*val = new;
return 1;
}else
return 0;
CAS汇编码:
TEXT runtime∕internal∕atomic·Cas(SB), NOSPLIT, $0-13
MOVLptr+0(FP), BX
MOVLold+4(FP), AX
MOVLnew+8(FP), CX
LOCK
CMPXCHGLCX, 0(BX)
SETEQret+12(FP)
RET
func main() {
a := 1
var mu sync.Mutex
go func() {
mu.Lock()
println("lock")
a += 2
//time.Sleep(time.Second)
time.Sleep(time.Second)
println("unlock")
mu.Unlock()
}()
go func() {
println("other")
a += 3
println("done")
}()
time.Sleep(time.Second * 5)
}
//print :
// lock
// other
// done
// unlock
Mutex使用
等待的goroutine执行的顺序是什么 非cpu中的goroutine的切换是有性能损耗的,正处于cpu切换的goroutine的切换不需要做上下文切换,如何设计以获得更好的性能 如果某个goroutine一直得不到调度怎么办 有的协程临界资源可能很快,但如果恰好其他线程抢锁没抢到,那它就要去排队吗?有没有啥方法让这个协程多抢一会
欧阳狂霸小课堂
<<< 左右滑动见更多 >>>
func main() {
a := 1
var mu sync.Mutex
go func() {
mu.Lock()
println("lock")
a += 2
//time.Sleep(time.Second)
time.Sleep(time.Second)
}()
go func() {
a += 3
println("unlock")
println(a)
mu.Unlock()
}()
time.Sleep(time.Second * 5)
}
func concurIncr() {
var wg sync.WaitGroup
var mu sync.Mutex
wg.Add(10)
var a int
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
for j := 0; j < 1000; j++ {
mu.Lock()
a++
mu.Unlock()
}
}()
}
wg.Wait()
println(a) // 10000
}
type SafeCounter struct {
mu sync.Mutex
v map[string]int
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mu.Unlock()
}
func (c *SafeCounter) Value(key string) int {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mu.Unlock()
return c.v[key]
}
func foo() {
mu.Lock()
defer mu.Unlock()
// 如果不用defer
err := ...
if err != nil{
//log error
return //需要在这里Unlock()
}
return //需要在这里Unlock()
}
func (t *Transport) CloseIdleConnections() {
t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
t.idleMu.Lock()
m := t.idleConn
t.idleConn = nil
t.closeIdle = true // close newly idle connections
t.idleLRU = connLRU{}
t.idleMu.Unlock()
for _, conns := range m {
for _, pconn := range conns {
pconn.close(errCloseIdleConns)
}
}
if t2 := t.h2transport; t2 != nil {
t2.CloseIdleConnections()
}
}
Mutex易错点
Panic
func misuse() {
var mu sync.Mutex
mu.Unlock() // fatal error: sync: unlock of unlocked mutex
}
死锁
type DataStore struct {
sync.Mutex // ← this mutex protects the cache below
cache map[string]string
}
func (ds *DataStore) get(key string) string {
ds.Lock()
defer ds.Unlock()
if ds.count() > 0 { <-- count() also takes a lock!
item := ds.cache[key]
return item
}
return ""
}
func (ds *DataStore) count() int {
ds.Lock()
defer ds.Unlock()
return len(ds.cache)
}
锁的粒度
// Don't do the following if you can avoid it
func doSomething() {
mu.Lock()
item := cache["myKey"]
http.Get() // Some expensive io call
mu.Unlock()
}
// Instead do the following where possible
func doSomething(){
mu.Lock()
item := cache["myKey"]
mu.Unlock()
http.Get() // This can take awhile and it's okay!
}
- EOF -
推荐阅读 点击标题可跳转3、深入理解 Go scheduler 调度器:GPM 源码分析
看完本文有收获?请分享给更多人
推荐关注「Linux 爱好者」,提升Linux技能
点赞和在看就是最大的支持❤️