1 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
您不需要將WaitGroup
實(shí)例傳遞給 goroutine,因?yàn)槟褂玫氖呛瘮?shù)文字,您可以直接引用在周圍函數(shù)中聲明的變量。
您也可以省略第二個(gè) 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 關(guān)注
- 122 瀏覽
添加回答
舉報(bào)