我正在尝试优化在IF语句中运行多个函数的验证过程,因此我试图使用go的并发来解决这个问题,但它不起作用。
我运行以下代码并尝试了很多不同的方法来实现通道关闭和等待组,但我不断收到以下错误:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main.func1(0xc000074f60, 0x3, 0x3, 0xc000024180, 0xc0000241e0)
/home/raphael/projects/go/go-herupaa/main.go:24 +0x9f
main.main()
/home/raphael/projects/go/go-herupaa/main.go:25 +0xcb
goroutine 6 [chan send]:
main.a1(0xc0000241e0)
/home/raphael/projects/go/go-herupaa/main.go:49 +0x72
created by main.main.func1
/home/raphael/projects/go/go-herupaa/main.go:22 +0x71
goroutine 7 [chan send]:
main.a2(0xc0000241e0)
/home/raphael/projects/go/go-herupaa/main.go:56 +0x72
created by main.main.func1
/home/raphael/projects/go/go-herupaa/main.go:22 +0x71
goroutine 8 [chan send]:
main.a3(0xc0000241e0)
/home/raphael/projects/go/go-herupaa/main.go:63 +0x72
created by main.main.func1
/home/raphael/projects/go/go-herupaa/main.go:22 +0x71
exit status 2
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
v := []func(chan<- bool){
a1,
a2,
a3,
}
q := make(chan bool)
c := make(chan bool)
func(c chan bool) {
for _, f := range v {
wg.Add(1)
go f(c)
}
q <- true
}(c)
p := receive(c, q)
fmt.Println(p)
wg.Wait()
}
func receive(c, q chan bool) bool {
for {
select {
case v := <-c:
if !v {
fmt.Println("Received ", v)
return false
}
case <-q:
fmt.Println("Received Exit")
return true
}
}
}
func a1(c chan<- bool) {
defer wg.Done()
time.Sleep(time.Millisecond * 2000)
c <- true
fmt.Println("Finish 1")
}
func a2(c chan<- bool) {
defer wg.Done()
time.Sleep(time.Millisecond * 2000)
c <- true
fmt.Println("Finish 2")
}
func a3(c chan<- bool) {
defer wg.Done()
time.Sleep(time.Millisecond * 2000)
c <- true
fmt.Println("Finish 3")
}
去
喵喵时光机
有只小跳蛙
相关分类