package main
import (
"time"
"runtime"
)
var c = make(chan int, 2)
func main() {
go worker(1)
for i := 0; i < 30; i++ {
go func() {
// k := i make a local copy not make any difference
c <- i
}()
}
time.Sleep(100* time.Second)
}
func worker(id int) {
for {
a := <-c
println(a, runtime.NumGoroutine())
time.Sleep(time.Second)
}
}
the output is unpredictable, sometimes like below.
7 9
13 29
13 28
13 27
13 26
13 25
13 24
13 23
16 22
16 21
17 20
19 19
21 18
21 17
23 16
25 15
26 14
26 13
26 12
26 11
26 10
26 9
26 8
26 7
27 6
27 5
13 4
28 3
30 2
30 2
I know sender will block if the buffer channel is full, and when channel is available the sender can continue.
- why output is not constant output 0-29? how to make it??
- how variable/local variable store in goroutine??
- if lots of senders are blocked, are they waked up by FIFO order??