从 goroutine 中接收多个返回值
时间:2024-02-21
浏览:192
作者:佚名
怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《从 goroutine 中接收多个返回值》,涉及到,有需要的可以收藏一下
问题内容
我正在尝试用 Go 编写 wc(1),并且正在尝试使用 goroutine 来更有效地计算大量输入文件。我的代码工作正常,但我很难实现一种方法来总结所有 go 例程的统计信息。如何将函数变量 nl、nw、nc 传递给 main,并在所有 go 例程完成工作后在那里汇总它们?
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
ch := make(chan string)
for _, arg := range os.Args[1:] {
go wc(arg, ch)
}
for range os.Args[1:] {
fmt.Println(<-ch)
}
// Todo: summarize results...
}
func wc(arg string, ch chan<- string) {
nl, nw, nc := 0, 0, 0
file, err := os.Open(arg)
if err != nil {
fmt.Println("Can't open file: %v", err)
}
defer file.Close()
scan := bufio.NewScanner(file)
for scan.Scan() {
nl++
line := scan.Text()
words := bufio.NewScanner(strings.NewReader(line))
words.Split(bufio.ScanWords)
for words.Scan() {
nw++
}
runes := bufio.NewReader(strings.NewReader(line))
for {
if _, _, err := runes.ReadRune(); err != nil {
break
} else {
nc++
}
}
}
ch <- fmt.Sprintf("%8d%8d%8d", nl, nw, nc+nl)
}正确答案
您已经接近答案了!我建议快速重构,返回带有数字的 Result 对象,这将允许轻松地在末尾添加它们(而不是使用字符串)。因此,您可以使用 chan 结果 而不是 chan string。
基本上,您可以引入一个 totalResult 变量,并且在迭代所有结果时,只需将 nl、nc 和 nw 的结果添加到该总变量中。
package main
import (
"fmt"
"math/rand"
)
// define a struct to hold the result
type Result struct {
nl int
nw int
nc int
}
// this is to be able to use fmt.Println(result)
func (r Result) String() string {
return fmt.Sprintf("%8d%8d%8d", r.nl, r.nw, r.nc+r.nl)
}
func main() {
ch := make(chan Result)
for _, arg := range os.Args[1:] {
go wc(arg, ch)
}
totalResult := Result{}
for range os.Args[1:] {
result := <-ch
fmt.Println(result) // just for debugging
// sum everything
totalResult.nl += result.nl
totalResult.nw += result.nw
totalResult.nc += result.nc
}
fmt.Println("Total result:")
fmt.Println(totalResult)
}
func wc(arg string, ch chan<- Result) {
nl, nw, nc := 0, 0, 0
// your logic to compute nl, nw, nc goes here
ch <- Result{nl: nl, nw: nw, nc: nc + nl}
}
您应该得到类似这样的内容(包含 3 个文件):
37 50 4753
19 106 821
47 255 3806
Total result:
103 411 9380到这里,我们也就讲完了《从 goroutine 中接收多个返回值》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
热门专题
