我是统计信息收集的样本,其中我在结构内使用了go通道,从逻辑上看对我来说是正确的,但我无法通过以下代码找到问题,只是不打印值已添加。
package main
import (
"fmt"
"math/rand"
"time"
)
//StatsMessage will hold single stats entry
type StatsMessage struct {
Name string
Value int64
}
//StatsCollector will hold collected stats
type StatsCollector struct {
msgchan chan StatsMessage
messages []StatsMessage
done chan int
}
//Init will start a go routine
func (s StatsCollector) Init() {
s.msgchan = make(chan StatsMessage)
s.done = make(chan int)
s.messages = make([]StatsMessage, 0)
go s.fillMessages()
}
//AddStats adds a single stats in a Messages
func (s StatsCollector) AddStats(name string, value int64) {
msg := StatsMessage{Name: name, Value: value}
s.msgchan <- msg
fmt.Println("Message added")
}
func (s StatsCollector) fillMessages() {
fmt.Println("Filler started...")
for {
s.messages = append(s.messages, <-s.msgchan)
fmt.Println("Added to messages")
}
}
func generateStats(s *StatsCollector) {
for {
select {
case <-time.After(1 * time.Second):
fmt.Println("Generated message...")
s.AddStats("my_first_stats", rand.Int63())
case <-s.done:
fmt.Println("Stop generating")
return
}
}
}
func flushStats(s *StatsCollector) {
for _, stat := range s.messages {
fmt.Println(stat.Name, stat.Value)
}
}
func main() {
s := &StatsCollector{}
s.Init()
go generateStats(s)
time.Sleep(5 * time.Second)
flushStats(s)
}
如果我在StatsCollector对象创建时提供了结构字段,那么它确实可以工作