我有一个我无法解决的死锁问题。
我拥有一些 url,goroutine 中的每个 url 都会给我带来足够的数据。我将这些数据放入单个通道中。但是,如果我关闭频道,程序将无法运行,如果我离开频道,则会出现打开死锁。
不知道怎么解决,求大神解答
下面我把问题简化一下
package main
import (
"fmt"
)
type urlNumbers struct {
url string
numbers []int
}
func getNumbers(urls []urlNumbers) chan int {
ch := make(chan int)
for _, url := range urls {
go allNumbersOfURL(url, ch)
}
return ch
}
func allNumbersOfURL(url urlNumbers, ch chan int) {
for _, i := range url.numbers {
ch <- i
}
}
func main() {
url1 := urlNumbers {url: "1", numbers: []int{1, 2, 3}}
url2 := urlNumbers {url: "2", numbers: []int{4, 5, 6}}
url3 := urlNumbers {url: "3", numbers: []int{7, 8, 9}}
url4 := urlNumbers {url: "4", numbers: []int{10, 11, 12}}
c := getNumbers([]urlNumbers{url1, url2, url3, url4})
for i := range c {
fmt.Println(i)
}
fmt.Println("END")
}
输出
go run app.go
10
11
12
4
7
1
2
3
5
6
8
9
fatal error: all goroutines are asleep - deadlock!
杨__羊羊
江户川乱折腾
相关分类