[英]golang chanel not working with sync.WaitGroup
我的代碼
package main
import (
"fmt"
"sync"
)
func other(c chan int, wg *sync.WaitGroup) {
c <- 455
wg.Done()
}
func addInt(c chan int, d int, wg *sync.WaitGroup) {
c <- d
wg.Done()
}
func main() {
var wg sync.WaitGroup
myChanel := make(chan int)
wg.Add(2)
go addInt(myChanel, 5, &wg)
go other(myChanel, &wg)
wg.Wait()
c := 0
for v := range myChanel {
if c == 1 {
close(myChanel)
}
fmt.Println(v)
c++
}
}
我正在學習 golang 查看地雷,但確實我遇到了這樣的錯誤。 我查看了其他來源。 我無法找到一個健康的解決方案。 我再次嘗試關閉(香奈兒)。
錯誤輸出
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xc0000140f8)
/usr/lib/go-1.13/src/runtime/sema.go:56 +0x42
sync.(*WaitGroup).Wait(0xc0000140f0)
/usr/lib/go-1.13/src/sync/waitgroup.go:130 +0x64
main.main()
/home/zeus/go/src/github.com/awesomeProject/pool.go:27 +0xe4
goroutine 6 [chan send]:
main.addInt(0xc000016120, 0x5, 0xc0000140f0)
/home/zeus/go/src/github.com/awesomeProject/pool.go:14 +0x3f
created by main.main
/home/zeus/go/src/github.com/awesomeProject/pool.go:24 +0xaa
goroutine 7 [chan send]:
main.other(0xc000016120, 0xc0000140f0)
/home/zeus/go/src/github.com/awesomeProject/pool.go:9 +0x37
created by main.main
/home/zeus/go/src/github.com/awesomeProject/pool.go:25 +0xd6
exit status 2
你有一個無緩沖的通道,這意味着你不能在它上面發送,直到有東西等待接收。
所以當你這樣做時:
wg.Wait()
在你做之前
for v := range myChanel
你永遠無法到達接收器。
無論如何,在使用無緩沖通道時,我從來不需要使用等待組,根據我的經驗,只有在沒有通道的情況下執行並發操作時才需要它們。 你可以這樣做: https : //play.golang.org/p/-SUuXGlFd1E
我解決了
package main
import (
"fmt"
"sync"
"time"
)
func other(c chan int, wg *sync.WaitGroup) {
time.Sleep(time.Second*1)
c <- 455
wg.Done()
}
func addInt(c chan int, d int, wg *sync.WaitGroup) {
c <- d
wg.Done()
}
func main() {
var wg sync.WaitGroup
myChanel := make(chan int)
wg.Add(2)
go addInt(myChanel, 5, &wg)
go other(myChanel, &wg)
go func() {
wg.Wait()
close(myChanel)
}()
for v := range myChanel {
fmt.Println(v)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.