在并發(fā)編程中,當(dāng)多個(gè) goroutine 需要訪問(wèn)共享資源時(shí),我們需要使用一些機(jī)制來(lái)協(xié)調(diào)它們的執(zhí)行順序,以避免競(jìng)態(tài)條件和數(shù)據(jù)不一致的問(wèn)題。在 Go 語(yǔ)言中,sync.Cond 條件變量就是一種常用的機(jī)制,它可以用來(lái)等待和通知其他 goroutine。
互斥鎖(sync.Mutex)用于保護(hù)臨界區(qū)和共享資源,而 sync.Cond 則用于協(xié)調(diào)多個(gè) goroutine 的執(zhí)行順序?;コ怄i只能一個(gè) goroutine 持有鎖,其他 goroutine 必須等待鎖被釋放才能繼續(xù)執(zhí)行。而 sync.Cond 可以讓等待的 goroutine 在條件滿足時(shí)被喚醒,進(jìn)而繼續(xù)執(zhí)行。
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}
每個(gè) Cond 實(shí)例都會(huì)關(guān)聯(lián)一個(gè)鎖 L(互斥鎖 *Mutex,或讀寫(xiě)鎖 *RWMutex),當(dāng)修改條件或者調(diào)用 Wait 方法時(shí),必須加鎖。
func NewCond(l Locker) *Cond
NewCond 方法用于創(chuàng)建一個(gè) Cond 實(shí)例,并關(guān)聯(lián)一個(gè)鎖(互斥鎖或讀寫(xiě)鎖)。
// 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。它不需要持有鎖來(lái)調(diào)用。
// 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 方法用于喚醒一個(gè)等待條件變量 c 的 goroutine。它不需要持有鎖來(lái)調(diào)用。
// 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()
Wait 方法會(huì)自動(dòng)釋放鎖,并掛起當(dāng)前的 goroutine,直到條件變量 c 被 Broadcast 或 Signal 喚醒。被喚醒后,Wait 方法會(huì)重新獲得鎖,并繼續(xù)執(zhí)行后續(xù)的代碼。
下面是一個(gè)使用 sync.Cond 的示例,實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的讀寫(xiě)同步機(jī)制:
package mainimport ( "fmt" "sync" "time")var done = falsefunc read(str string, c *sync.Cond) { c.L.Lock() for !done { c.Wait() } fmt.Println(str, "start reading") c.L.Unlock()}func write(str string, c *sync.Cond) { fmt.Println(str, "start writing") time.Sleep(2 * time.Second) c.L.Lock() done = true c.L.Unlock() fmt.Println(str, "wake up all") c.Broadcast()}func main() { m := &sync.Mutex{} c := sync.NewCond(m) go read("reader1", c) go read("reader2", c) write("writer", c) time.Sleep(5 * time.Second)}
在這個(gè)示例中,有兩個(gè)讀取協(xié)程(reader1 和 reader2)和一個(gè)寫(xiě)入?yún)f(xié)程(writer)。寫(xiě)入?yún)f(xié)程在執(zhí)行后會(huì)通知所有等待的讀取協(xié)程,讀取協(xié)程在條件滿足時(shí)才能開(kāi)始讀取。
輸出結(jié)果如下:
writer start writingwriter wake up allreader2 start readingreader1 start reading
通過(guò)使用 sync.Cond,我們可以很方便地實(shí)現(xiàn)多個(gè) goroutine 之間的等待和通知機(jī)制,從而更好地協(xié)調(diào)并發(fā)訪問(wèn)共享資源的執(zhí)行順序。
本文鏈接:http://www.www897cc.com/showinfo-26-34582-0.html使用 sync.Cond 來(lái)協(xié)調(diào)并發(fā) goroutine 的訪問(wèn)共享資源
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com