2 回答

TA貢獻1811條經驗 獲得超5個贊
您的 WaitGroup.Add 和 WaitGroup.Done 調用不匹配。然而,在這種情況下,“我完成了”信號通常是通過關閉輸出通道來給出的。僅當工作在多個 goroutine 之間共享時才需要 WaitGroups(即多個 goroutine 消耗相同的通道),但這里的情況并非如此。
package main
import (
? ? "fmt"
)
func main() {
? ? a1 := []string{"apple", "apricot"}
? ? chan1 := make(chan string)
? ? chan2 := make(chan string)
? ? chan3 := make(chan string)
? ? go func() {
? ? ? ? for _, s := range a1 {
? ? ? ? ? ? chan1 <- s
? ? ? ? }
? ? ? ? close(chan1)
? ? }()
? ? go Pipe1(chan2, chan1)
? ? go Pipe2(chan3, chan2)
? ? // This range loop terminates when chan3 is closed, which Pipe2 does after
? ? // chan2 is closed, which Pipe1 does after chan1 is closed, which the
? ? // anonymous goroutine above does after it sent all values.
? ? for s := range chan3 {
? ? ? ? fmt.Println(s)
? ? }
}
func Pipe1(out chan<- string, in <-chan string) {
? ? for s := range in {
? ? ? ? out <- s + "s are"
? ? }
? ? close(out) // let caller know that we're done
}
func Pipe2(out chan<- string, in <-chan string) {
? ? for s := range in {
? ? ? ? out <- s + " good for you"
? ? }
? ? close(out) // let caller know that we're done
}
在操場上嘗試一下:https ://play.golang.org/p/d2J4APjs_lL

TA貢獻1820條經驗 獲得超2個贊
您正在調用wg.Wait
一個 goroutine,因此main
可以在其他例程完成之前返回(因此您的程序退出)。這會導致您看到的行為,但僅從 Goroutine 中取出是不夠的。
您還濫用了WaitGroup
一般性;你的Add
和Done
調用 彼此不相關,并且你沒有那么多Done
s Add
,所以 sWaitGroup
永遠不會完成。如果您在循環中調用Add
,則每次循環迭代也必須導致調用Done
;正如您現在所擁有的,您defer wg.Done()
在每個循環之前,然后Add
在循環內部調用,從而產生一個Done
和多個Add
s。該代碼需要進行重大修改才能按預期工作。
- 2 回答
- 0 關注
- 152 瀏覽
添加回答
舉報