Gocondition variable
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 Locker
type Locker interface {
Lock()
Unlock()
}
A Locker represents an object that can be locked and unlocked.
NewCond()LockerBroadcast()condition variablegoroutineSignal()goroutineWait()goroutinecondition variable
c.L.Lock()
for !condition() {
c.Wait()
}
... make use of condition ...
c.L.Unlock()
Wait()Wait()wait()goroutinegoroutine
package main
import (
"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")
}
一次执行结果如下:
Enter Thread ID: 2
Enter loop: Thread ID: 2
Enter Thread ID: 1
Enter loop: Thread ID: 1
Sleep 1 second
Exit loop: Thread ID: 2
Exit Thread ID: 2
Exit loop: Thread ID: 1
Enter loop: Thread ID: 1
Program exit
goroutine 2goroutine 1goroutinecondition variable
参考资料:
Package sync;
Condition Variables。