This is a creation in Article, where the information may have evolved or changed.
GoThe Language Sync package provides the conditional variable ( condition variable ) type:
type Cond struct { // L is held while observing or changing the condition L Locker // contains filtered or unexported fields}type Cond func NewCond(l Locker) *Cond func (c *Cond) Broadcast() func (c *Cond) Signal() func (c *Cond) Wait()type Lockertype Locker interface { Lock() Unlock()}A Locker represents an object that can be locked and unlocked.
NewCond()The function input parameter is an Locker interface type, which is a variable that implements the lock function. The Broadcast() function notifies all the condition variable waiting goroutine , and the Signal() function notifies only one of them goroutine . Wait()will let goroutine the block in condition variable , wait for the condition to set up. The usual practice is to:
c.L.Lock()for !condition() { c.Wait()}... make use of condition ...c.L.Unlock()
Wait()the entry function will unlock and the Wait() function will be unlocked again. Due to the logic of re-locking in "unlock-and-Receive notifications", it is possible that another same wait() goroutine preemptive step changes the condition, causing goroutine the current condition to cease to be true, so this block uses loop detection. Refer to the following example:
package mainimport ( "sync" "time" "fmt")func main() { c := sync.NewCond(&sync.Mutex{}) var num int for i := 1; i <= 2; i++ { go func(id int) { fmt.Println("Enter Thread ID:", id) c.L.Lock() for num != 1 { fmt.Println("Enter loop: Thread ID:", id) c.Wait() fmt.Println("Exit loop: Thread ID:", id) } num++ c.L.Unlock() fmt.Println("Exit Thread ID:", id) }(i) } time.Sleep(time.Second) fmt.Println("Sleep 1 second") num++ c.Broadcast() time.Sleep(time.Second) fmt.Println("Program exit")}
The results of one execution are as follows:
Enter Thread ID: 2Enter loop: Thread ID: 2Enter Thread ID: 1Enter loop: Thread ID: 1Sleep 1 secondExit loop: Thread ID: 2Exit Thread ID: 2Exit loop: Thread ID: 1Enter loop: Thread ID: 1Program exit
As can be seen from the above example, due to goroutine 2 the change of conditions, leading to goroutine 1 re-enter the cycle, that is, multiple goroutine blocking in one condition variable of the existence of a competitive relationship.
Resources:
Package sync;
Condition Variables.