Go condition example
- cond.go
/*
* Author, Copyright: Oleg Borodin <onborodin@gmail.com>
*/
package main
import (
"fmt"
"sync"
"time"
)
type Printer struct {
cond *sync.Cond
id string
message string
}
func (this *Printer) Print() {
for {
this.cond.L.Lock()
this.cond.Wait()
this.cond.L.Unlock()
fmt.Println(this.id, this.message)
}
}
func NewPrinter(id, message string, cond *sync.Cond) *Printer {
var printer Printer
printer.message = message
printer.id = id
printer.cond = cond
return &printer
}
func main() {
var mtx sync.Mutex
cond := sync.NewCond(&mtx)
message := "hi"
p1 := NewPrinter("001", message, cond)
p2 := NewPrinter("002", message, cond)
go p1.Print()
go p2.Print()
fmt.Println("#sleep")
time.Sleep(1 * time.Second)
fmt.Println("#broadcast")
cond.Broadcast()
fmt.Println("#sleep")
time.Sleep(1 * time.Second)
fmt.Println("#signal")
cond.Signal()
fmt.Println("#sleep")
time.Sleep(1 * time.Second)
fmt.Println("#signal")
cond.Signal()
fmt.Println("#sleep")
time.Sleep(1 * time.Second)
fmt.Println("#signal")
cond.Signal()
time.Sleep(3 * time.Second)
}
//EOF
Out
$ go run untitled.go
#sleep
#broadcast
#sleep
002 hi
001 hi
#signal
#sleep
002 hi
#signal
#sleep
001 hi
#signal