我已将以下内容添加到 stdout 和 stderr goroutine (go func() …) 以等待获取output并error完成。现在我希望外部函数将等待两个例程完成。func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {scanout := bufio.NewScanner(stdout)scanout.Split(bufio.ScanRunes)go func() { for scanout.Scan() { fmt.Print(scanout.Text()) }}()go func() {scanerr.Split(bufio.ScanRunes) for scanerr.Scan() { fmt.Print(scanerr.Text()) }}()}现在我尝试添加等待组,但它不起作用,因为我不确定如何传递等待组实例,知道吗?func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {scanout := bufio.NewScanner(stdout)scanout.Split(bufio.ScanRunes)var waitgroup sync.WaitGroupwaitgroup.Add(1)go func() { for scanout.Scan() { fmt.Print(scanout.Text()) }}()waitgroup.Wait()waitgroup.Add(1)go func() {scanerr.Split(bufio.ScanRunes) for scanerr.Scan() { fmt.Print(scanerr.Text()) }}()waitgroup.Wait()}更新应该是这样吗?func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {scanout := bufio.NewScanner(stdout)scanout.Split(bufio.ScanRunes)var waitgroup sync.WaitGroupwaitgroup.Add(2)go func() { for scanout.Scan() { fmt.Print(scanout.Text()) }}()go func() {scanerr.Split(bufio.ScanRunes) for scanerr.Scan() { fmt.Print(scanerr.Text()) }}()waitgroup.Wait()}
1 回答
慕森卡
TA贡献1806条经验 获得超8个赞
您不需要将WaitGroup
实例传递给 goroutine,因为您使用的是函数文字,您可以直接引用在周围函数中声明的变量。
您也可以省略第二个 goroutine,它对于您的用例来说并不是真正需要的。
func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanout.Split(bufio.ScanRunes)
var wg sync.WaitGroup
wg.Add(1)
// exec scanout in its own goroutine
go func() {
for scanout.Scan() {
fmt.Print(scanout.Text())
}
wg.Done()
}()
// exec scanerr
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
// wait for scanout
wg.Wait()
}
- 1 回答
- 0 关注
- 96 浏览
添加回答
举报
0/150
提交
取消