I was trying to use sync.Cond - Wait and Broadcast. I could not understand some parts of it:
The comment for Wait calls says:
41 // Because c.L is not locked when Wait first resumes, the caller
42 // typically cannot assume that the condition is true when
43 // Wait returns. Instead, the caller should Wait in a loop:
44 //
45 // c.L.Lock()
46 // for !condition() {
47 // c.Wait()
48 // }
49 // ... make use of condition ...
50 // c.L.Unlock()
What is the reason this is required?
So this means the following program may not be correct (all though it works):
package main
import (
"bufio"
"fmt"
"os"
"sync"
)
type processor struct {
n int
c *sync.Cond
started chan int
}
func newProcessor(n int) *processor {
p := new(processor)
p.n = n
p.c = sync.NewCond(&sync.Mutex{})
p.started = make(chan int, n)
return p
}
func (p *processor) start() {
for i := 0; i < p.n; i++ {
go p.process(i)
}
for i := 0; i < p.n; i++ {
<-p.started
}
p.c.L.Lock()
p.c.Broadcast()
p.c.L.Unlock()
}
func (p *processor) process(f int) {
fmt.Printf("fork : %d
", f)
p.c.L.Lock()
p.started <- f
p.c.Wait()
p.c.L.Unlock()
fmt.Printf("process: %d - out of wait
", f)
}
func main() {
p := newProcessor(5)
p.start()
reader := bufio.NewReader(os.Stdin)
_,_ =reader.ReadString('
')
}