当前位置: > > > > golang 的范围与静态通道长度
golang 的范围与静态通道长度
来源:stackoverflow
2024-04-30 22:30:35
0浏览
收藏
从现在开始,我们要努力学习啦!今天我给大家带来《golang 的范围与静态通道长度》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!
问题内容
我有一个通道获取从日志文件解析的事件,另一个通道用于同步。我的测试共有 8 个事件。
当使用 for range 语法时,我收到 4 个事件。当使用已知数字(8)时,我可以得到所有它们。
func TestParserManyOpinit(t *testing.T) {
ch := make(chan event.Event, 1000)
done := make(chan bool)
go parser.Parse("./test_data/many_opinit", ch, done)
count := 0
exp := 8
evtList := []event.Event{}
<-done
close(ch)
//This gets all the events
for i := 0; i < 8; i++ {
evtList = append(evtList, <-ch)
count++
}
//This only gives me four
//for range ch {
// evtList = append(evtList, <-ch)
// count++
//}
if count != exp || count != len(evtList) {
t.Errorf("Not proper lenght, got %d, exp %d, evtList %d", count, exp, len(evtList))
}
func Parse(filePath string, evtChan chan event.Event, done chan bool) {
log.Info(fmt.Sprintf("(thread) Parsing file %s", filePath))
file, err := os.Open(filePath)
defer file.Close()
if err != nil {
log.Error("Cannot read file " + filePath)
}
count := 0
scan := bufio.NewScanner(file)
scan.Split(splitFunc)
scan.Scan() //Skip log file header
for scan.Scan() {
text := scan.Text()
text = strings.Trim(text, "\n")
splitEvt := strings.Split(text, "\n")
// Some parsing ...
count++
evtChan <- evt
}
fmt.Println("Done ", count) // gives 8
done <- true
}
我一定错过了与通道上的 for 循环相关的内容。
我尝试在 done <- true 部分之前添加 time.sleep 。它没有改变结果。
解决方案
当您使用 作为 range 时,每次循环迭代都会从通道中读取数据,并且您不会使用读取的值。因此,一半的值被丢弃。应该是:
for ev := range ch {
evtList = append(evtList, ev)
count++
}
为了实际利用循环迭代器中读取的值。
通道测距在 中进行了演示,在 中详细介绍。
好了,本文到此结束,带大家了解了《golang 的范围与静态通道长度》,希望本文对你有所帮助!关注米云公众号,给大家分享更多Golang知识!
