2 回答

TA贡献1725条经验 获得超7个赞
使用计数器关闭您的频道不是一个好习惯。您可以使用sync.WaitGroup. 这使您可以更好地控制何时关闭频道:
func main() {
var wg sync.WaitGroup
ch := make(chan string)
file, _ := os.Create("myfile.txt")
for i := 0; i < 100000; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
options := [3]string{"0", "1", "2"}
str := fmt.Sprintf("%6d ", i)
for j := 0; j < 40000; j++ {
str += options[rand.Intn(3)]
}
str += "\n"
ch <- str
}(i)
}
go func() {
wg.Wait()
close(ch)
}()
for result := range ch {
io.WriteString(file, result)
}
file.Close()
}

TA贡献1765条经验 获得超5个赞
看看能不能解决你的问题。。
func main() {
file, _ := os.Create("myfile.txt")
ch := make(chan string)
wg := new(sync.WaitGroup)
for i := 0; i < 100000; i++ {
wg.Add(1)
go generate(i, ch)
}
go func(){wg.Wait();close(ch)}()
counter := 0
for result := range ch {
counter++
io.WriteString(file, result)
}
file.Close()
}
func generate(id int, c chan string) {
options := [3]string{"0", "1", "2"}
str := fmt.Sprintf("%6d ", id)
for j := 0; j < 40000; j++ {
str += options[rand.Intn(3)]
}
str += "\n"
c <- str
wg.Done()
}
- 2 回答
- 0 关注
- 124 浏览
添加回答
举报