I'm a golang newer, today I met a time.Tick problem, it lets me very confuse, please see the following code
var MAX_LEN4 = 5000
func main() {
ch := make(chan struct{}, 100)
var length uint = 0
start := time.Now()
var wg sync.WaitGroup
wg.Add(1)
go func() {
tick := time.Tick(1 * time.Second)
for {
if length > MAX_LEN4+1 {
break
}
<-tick
fmt.Printf("Calculated: %d, time: %f
", length, time.Since(start).Seconds())
}
wg.Done()
}()
for ; length <= MAX_LEN4+1; length++ {
go test3(length, &ch)
}
wg.Wait()
fmt.Println("Test Finished")
}
func test3(l uint, ch *chan struct{}) {
NewEncoder()
// do something
}
type Encoder struct {
stream []byte
offset uint
//bitLeft uint
}
func NewEncoder() Encoder {
return Encoder{make([]byte, 4)}
}
when struct Encoder has []byte slice, the tick will block, the code will not print "Calculated..." content, and
<-tick
code will block there. like the above code
if struct Encoder doesn't a slice, but NewEncoder function returns a pointer, the tick doesn't work also, like the following code
func NewEncoder() *Encoder {
return &Encoder{4)}
}
only struct Encoder doesn't have []byte slice and NewEncoder function return non pointer Encoder, the tick will work fine.
I try to replace the code:
<-tick
by
time.Sleep(1 * time.Second)
the effect is the same
I don't know why the code?