熟悉Go編程的朋友都不會(huì)對(duì)sync
庫(kù)感到陌生估蹄,這個(gè)語(yǔ)言內(nèi)置庫(kù)提供了很多常見(jiàn)的處理并發(fā)編程的工具脸爱,今天就從最為小眾狞玛,使用最少的sync.Cond
庫(kù)說(shuō)起剖笙。
Cond是什么卵洗?
按照文檔的描述:
Cond implements a condition variable, a rendezvous point for goroutines waiting for or announcing the occurrence of an event.
大概意思就是Cond
實(shí)現(xiàn)了一種條件變量,用于描述事件(event)的發(fā)生或者作為goroutine的交匯點(diǎn)弥咪。
聽(tīng)起來(lái)似乎有點(diǎn)抽象过蹂,下面我們使用實(shí)際代碼來(lái)說(shuō)明。
現(xiàn)在引入一個(gè)實(shí)際問(wèn)題酪夷,如何當(dāng)一個(gè)變量為指定值時(shí)做一些特定的行為榴啸?比如,當(dāng)同時(shí)登陸用戶大于100時(shí)晚岭,做一些額外的動(dòng)作鸥印。
首先,我們可以在變量產(chǎn)生變化的時(shí)候主動(dòng)做檢查坦报,看是否觸發(fā)了條件(這種方法固然可行库说,但是不在今天的考慮范疇)。其次片择,我們可以通過(guò)輪詢的方式潜的,來(lái)檢查值是否達(dá)到了指定的條件,這種方式的好處在于字管,處理變量變化的動(dòng)作與額外觸發(fā)的行為可以完全分隔開(kāi)啰挪,有利于代碼解耦信不。
一個(gè)簡(jiǎn)單的輪詢邏輯很容易實(shí)現(xiàn):
for {
mu.RLock()
func() {
defer mu.RUnlock()
if len(users) >= 100 {
funcDoSomething()
}
}()
}
不出意外的,這段代碼在非搶占調(diào)度下會(huì)占用一整個(gè)處理器的資源(因?yàn)槭且粋€(gè)無(wú)限死循環(huán)且沒(méi)有syscall去主動(dòng)讓出處理器控制器)亡呵。
一個(gè)最容易想到的簡(jiǎn)單優(yōu)化是抽活,在for循環(huán)中加上一個(gè)sleep
時(shí)間,這樣對(duì)于cpu的占用就會(huì)低很多锰什。
更理想的行為是下硕,當(dāng)且僅當(dāng)條件發(fā)生變化的時(shí)候(這里的條件是users長(zhǎng)度),才做后續(xù)的工作汁胆。
使用Cond
在代碼實(shí)現(xiàn)上大概是:
cond.L.Lock()
for len(users) < 100 {
cond.Wait()
}
funcDoSomething()
cond.L.Unlock()
// in some other goroutine:
cond.L.Lock()
users = append(users, newUser)
cond.L.Unlock()
cond.Signal()
不難發(fā)現(xiàn)梭姓,其實(shí)上面的代碼可以通過(guò)channel
做簡(jiǎn)單實(shí)現(xiàn):
select{
case <-ch:
if len(users)>=100{
funcDoSomething()
}
default:
}
// in some other goroutine:
mu.Lock()
users = append(users, newUser)
mu.Unlock()
ch<-struct{}{}
上面兩段代碼在邏輯上其實(shí)是等價(jià)的。這么看來(lái)嫩码,Cond
并沒(méi)有解決什么復(fù)雜問(wèn)題嘛誉尖,怪不得大家都不關(guān)注它。其實(shí)Cond
主要有用的并不是Signal
模式谢谦,而是Broadcast
模式释牺。
其實(shí)在API的使用上面,Signal
與Broadcast
并無(wú)不同回挽。兩者主要解決的場(chǎng)景差異在于:Signal
會(huì)喚醒任意一個(gè)處于Wait
狀態(tài)的goroutine没咙;而Broadcast
則會(huì)喚醒所有處于Wait
狀態(tài)的goroutine。我們?cè)谑褂胏hannel做類似模式的時(shí)候千劈,很容易可以通過(guò)一個(gè)send操作來(lái)模仿Signal
祭刚,而Broadcast
就不那么容易(直接close channel是一個(gè)方案,問(wèn)題在于close動(dòng)作只能發(fā)生一次墙牌,而Broadcast
則可以發(fā)生多次)涡驮。
用channel實(shí)現(xiàn)Cond
模式(約束在于Broadcast
只能實(shí)現(xiàn)一次):
type Cond struct {
L sync.Mutex // used by caller
ch chan struct{}
}
func (c *Cond) Wait() {
ch := c.ch
c.L.Unlock()
<-ch
c.L.Lock()
}
func (c *Cond) Signal() {
select {
case c.ch <- struct{}{}:
default:
}
}
func (c *Cond) Broadcast() {
close(c.ch)
c.ch = make(chan struct{})
}
Cond
的實(shí)際實(shí)現(xiàn)是:
type Cond struct {
noCopy noCopy
// L is held while observing or changing the condition
L Locker
notify notifyList
checker copyChecker
}
func NewCond(l Locker) *Cond {
return &Cond{L: l}
}
func (c *Cond) Wait() {
c.checker.check()
t := runtime_notifyListAdd(&c.notify)
c.L.Unlock()
runtime_notifyListWait(&c.notify, t)
c.L.Lock()
}
func (c *Cond) Signal() {
c.checker.check()
runtime_notifyListNotifyOne(&c.notify)
}
func (c *Cond) Broadcast() {
c.checker.check()
runtime_notifyListNotifyAll(&c.notify)
}