Go語言中sync.Cond使用詳解
sync.Cond 可以用來干什么?
Golang 的 sync 包中的 Cond 實現(xiàn)了一種條件變量,可以使用多個 Reader 等待公共資源。
每個 Cond 都會關(guān)聯(lián)一個 Lock ,當(dāng)修改條件或者調(diào)用 Wait 方法,必須加鎖,保護(hù) Condition。 有點類似 Java 中的 Wait 和 NotifyAll。
sync.Cond 條件變量是用來協(xié)調(diào)想要共享資源的那些 goroutine, 當(dāng)共享資源的狀態(tài)發(fā)生變化時,可以被用來通知被互斥鎖阻塞的 gorountine。
與 Sync.Mutex 的區(qū)別
sync.Cond 基于互斥鎖,和互斥鎖有什么區(qū)別?
sync.Mutex 通常用來保護(hù)臨界區(qū)和共享資源,條件變量 sync.Cond 用來協(xié)調(diào)想要訪問的共享資源。
sync.Cond 使用場景
有一個協(xié)程正在接收數(shù)據(jù),其他協(xié)程必須等待這個協(xié)程接收完數(shù)據(jù),才能讀取到正確的數(shù)據(jù)。
上述情形下,如果單純的使用 channel 或者互斥鎖,只能有一個協(xié)程可以等待,并讀取到數(shù)據(jù),沒辦法通知其他協(xié)程也讀取數(shù)據(jù)。
這個時候怎么辦?
- 可以用一個全局變量標(biāo)識第一個協(xié)程是否接收數(shù)據(jù)完畢,剩下的協(xié)程反復(fù)檢查該變量的值,直到讀取到數(shù)據(jù)。
- 也可創(chuàng)建多個 channel, 每個協(xié)程阻塞在一個 Channel 上,由接收數(shù)據(jù)的協(xié)程在數(shù)據(jù)接收完畢后,挨個通知。
然后 Go 中其實內(nèi)置來一個 sync.Cond 來解決這個問題。
sync.Cond
// Each Cond has an associated Locker L (often a *Mutex or *RWMutex), // which must be held when changing the condition and // when calling the Wait method. // // A Cond must not be copied after first use. type Cond struct { noCopy noCopy // L is held while observing or changing the condition L Locker notify notifyList checker copyChecker }
可以看到每個 Cond 都會關(guān)聯(lián)一個 鎖 L (互斥鎖 Mutex, 或者讀寫鎖 * RMMutex), 當(dāng)修改條件或者使用 Wait 的時候必須要加鎖。
sync.Cond 有哪些方法
NewCond 創(chuàng)建實例
func NewCond(l Locker) *Cond
NewCond 創(chuàng)建實例需要關(guān)聯(lián)一個鎖。
具體實例:
cadence := sync.NewCond(&sync.Mutex{})
Broadcast 廣播喚醒所有
// Broadcast wakes all goroutines waiting on c. // // It is allowed but not required for the caller to hold c.L // during the call. func (c *Cond) Broadcast()
Broadcast 喚醒所有等待條件變量 c 的 goroutine,無需鎖保護(hù)。
具體實例:
go func() { for range time.Tick(1 * time.Millisecond) { cadence.Broadcast() } }()
Signal 喚醒一個協(xié)程
// Signal wakes one goroutine waiting on c, if there is any. // // It is allowed but not required for the caller to hold c.L // during the call. func (c *Cond) Signal()
Signal 只喚醒任意1個等待條件變量 c 的 goroutine,無需鎖保護(hù)。 有點類似 Java 中的 Notify
Wait 等待
// Wait atomically unlocks c.L and suspends execution // of the calling goroutine. After later resuming execution, // Wait locks c.L before returning. Unlike in other systems, // Wait cannot return unless awoken by Broadcast or Signal. // // Because c.L is not locked when Wait first resumes, the caller // typically cannot assume that the condition is true when // Wait returns. Instead, the caller should Wait in a loop: // // c.L.Lock() // for !condition() { // c.Wait() // } // ... make use of condition ... // c.L.Unlock() // func (c *Cond) Wait()
調(diào)用 Wait 會自動釋放鎖 c.L,并掛起調(diào)用者所在的 goroutine,因此當(dāng)前協(xié)程會阻塞在 Wait 方法調(diào)用的地方。如果其他協(xié)程調(diào)用了 Signal 或 Broadcast 喚醒了該協(xié)程,Wait 方法結(jié)束阻塞時,并重新給 c.L 加鎖,并且繼續(xù)執(zhí)行 Wait 后面的代碼
代碼示例:
c.L.Lock() for !condition() { c.Wait() } ... make use of condition ... c.L.Unlock()
代碼示例
package sync import ( "log" "sync" "testing" "time" ) var done = false func read(name string, c *sync.Cond) { c.L.Lock() for !done { c.Wait() } log.Println(name, "starts reading") c.L.Unlock() } func write(name string, c *sync.Cond) { log.Println(name, "starts writing") time.Sleep(time.Second) c.L.Lock() done = true c.L.Unlock() log.Println(name, "wakes all") c.Broadcast() } func TestSyncCond(t *testing.T) { cond := sync.NewCond(&sync.Mutex{}) go read("reader1", cond) go read("reader2", cond) go read("reader3", cond) write("writer", cond) time.Sleep(time.Second * 3) }
運行結(jié)果
=== RUN TestSyncCond
2021/08/26 11:06:48 writer starts writing
2021/08/26 11:06:49 writer wakes all
2021/08/26 11:06:49 reader3 starts reading
2021/08/26 11:06:49 reader2 starts reading
2021/08/26 11:06:49 reader1 starts reading
--- PASS: TestSyncCond (4.01s)
PASS
到此這篇關(guān)于Go語言中sync.Cond使用詳解的文章就介紹到這了,更多相關(guān)Go sync.Cond內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang中按照結(jié)構(gòu)體的某個字段排序?qū)嵗a
在任何編程語言中,關(guān)乎到數(shù)據(jù)的排序都會有對應(yīng)的策略,下面這篇文章主要給大家介紹了關(guān)于golang中按照結(jié)構(gòu)體的某個字段排序的相關(guān)資料,需要的朋友可以參考下2022-05-05利用Go語言快速實現(xiàn)一個極簡任務(wù)調(diào)度系統(tǒng)
任務(wù)調(diào)度(Task Scheduling)是很多軟件系統(tǒng)中的重要組成部分,字面上的意思是按照一定要求分配運行一些通常時間較長的腳本或程序。本文將利用Go語言快速實現(xiàn)一個極簡任務(wù)調(diào)度系統(tǒng),感興趣的可以了解一下2022-10-10