H5W3
当前位置:H5W3 > go > 正文

【go】如何使用管道修改下述代码使其不会报deadlock?

package main
import (
"fmt"
)
func InitNum(ch chan int) {
for i := 1; i <= 2000; i++ {
ch <- i
}
close(ch)
}
func readNum(ch chan int, reschan chan map[int]int, remap chan bool) {
for {
temp, ok := <-ch
if !ok {
break
} else {
res := 0
remp1 := make(map[int]int)
for i := 1; i <= temp; i++ {
res = res + i
}
remp1[temp] = res
reschan <- remp1
}
}
}
func readMap(reschan chan map[int]int, remap chan bool) {
for {
temp, ok := <-reschan
if !ok {
fmt.Println("readMap break")
break
} else {
fmt.Println(temp)
}
}
remap <- true
close(remap)
}
func main() {
ch := make(chan int, 2000)
reschan := make(chan map[int]int, 2000)
remap := make(chan bool, 8)
for i := 0; i < 8; i++ {
go readNum(ch, reschan, remap)
go readMap(reschan, remap)
}
go InitNum(ch)
for i := 0; i < 8; i++ {
<-remap
}
}
package main
import (
"fmt"
)
func initNum(cr chan int) {
for i := 1; i <= 2000; i++ {
cr <- i
}
close(cr)
}
func readNum(cr chan int, chwritr chan map[int]int, re chan bool, i int) {
for {
temp, ok := <-cr
if !ok {
//time.Sleep(time.Second * 5)
break
}
result := 0
test := make(map[int]int)
for i := 1; i <= temp; i++ {
result = result + i
}
test[temp] = result
chwritr <- test
}
fmt.Printf("协程%d取不到数据退出\n", i)
re <- true
}
func main() {
cr := make(chan int, 2000)
chwritr := make(chan map[int]int, 2000)
re := make(chan bool, 9)
go initNum1(cr)
for i := 0; i < 9; i++ {
go readNum1(cr, chwritr, re, i)
}
go func() {
for i := 0; i < 9; i++ {
<-re
}
close(chwritr)
}()
for {
temp, ok := <-chwritr
if !ok {
break
}
fmt.Println(temp)
}
fmt.Println("主函数退出")
}

回答

本文地址:H5W3 » 【go】如何使用管道修改下述代码使其不会报deadlock?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址