Go語言中sync.Cond使用詳解
sync.Cond 可以用來干什么?
Golang 的 sync 包中的 Cond 實現(xiàn)了一種條件變量,可以使用多個 Reader 等待公共資源。
每個 Cond 都會關聯(lián)一個 Lock ,當修改條件或者調(diào)用 Wait 方法,必須加鎖,保護 Condition。 有點類似 Java 中的 Wait 和 NotifyAll。
sync.Cond 條件變量是用來協(xié)調(diào)想要共享資源的那些 goroutine, 當共享資源的狀態(tài)發(fā)生變化時,可以被用來通知被互斥鎖阻塞的 gorountine。
與 Sync.Mutex 的區(qū)別
sync.Cond 基于互斥鎖,和互斥鎖有什么區(qū)別?
sync.Mutex 通常用來保護臨界區(qū)和共享資源,條件變量 sync.Cond 用來協(xié)調(diào)想要訪問的共享資源。
sync.Cond 使用場景
有一個協(xié)程正在接收數(shù)據(jù),其他協(xié)程必須等待這個協(xié)程接收完數(shù)據(jù),才能讀取到正確的數(shù)據(jù)。
上述情形下,如果單純的使用 channel 或者互斥鎖,只能有一個協(xié)程可以等待,并讀取到數(shù)據(jù),沒辦法通知其他協(xié)程也讀取數(shù)據(jù)。
這個時候怎么辦?
- 可以用一個全局變量標識第一個協(xié)程是否接收數(shù)據(jù)完畢,剩下的協(xié)程反復檢查該變量的值,直到讀取到數(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 都會關聯(lián)一個 鎖 L (互斥鎖 Mutex, 或者讀寫鎖 * RMMutex), 當修改條件或者使用 Wait 的時候必須要加鎖。
sync.Cond 有哪些方法
NewCond 創(chuàng)建實例
func NewCond(l Locker) *Cond
NewCond 創(chuàng)建實例需要關聯(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,無需鎖保護。
具體實例:
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,無需鎖保護。 有點類似 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,因此當前協(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
到此這篇關于Go語言中sync.Cond使用詳解的文章就介紹到這了,更多相關Go sync.Cond內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Golang使用Gin創(chuàng)建Restful API的實現(xiàn)
本文主要介紹了Golang使用Gin創(chuàng)建Restful API的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01
golang實現(xiàn)對docker容器心跳監(jiān)控功能
這篇文章主要介紹了golang實現(xiàn)對docker容器心跳監(jiān)控功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
Golang基于Vault實現(xiàn)敏感數(shù)據(jù)加解密
數(shù)據(jù)加密是主要的數(shù)據(jù)安全防護技術之一,敏感數(shù)據(jù)應該加密存儲在數(shù)據(jù)庫中,降低泄露風險,本文將介紹一下利用Vault實現(xiàn)敏感數(shù)據(jù)加解密的方法,需要的可以參考一下2023-07-07
go語言通過odbc操作Access數(shù)據(jù)庫的方法
這篇文章主要介紹了go語言通過odbc操作Access數(shù)據(jù)庫的方法,實例分析了Go語言通過odbc連接、查詢與關閉access數(shù)據(jù)庫的技巧,需要的朋友可以參考下2015-03-03

