我有这段Go代码。我需要具备这种能力:在一个地方写入通道,然后在另一个地方读出它们(反之亦然):
package main
import "fmt"
var ch1=make(chan int)
var ch2=make(chan int)
func f1() {
select {
case <- ch1:fmt.Println("ch1")
default: fmt.Println("default")
}
}
func f2() {
select {
case <- ch2:fmt.Println("ch2")
default: fmt.Println("default")
}
}
func main() {
go f1()
go f2()
ch1<-1
ch2<-2
}
它总是像这样打印:
default
ch1
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox970110849/prog.go:22 +0xa0
此外我尝试了这个:
package main
import (
"fmt"
"sync"
)
var ch1=make(chan int)
var ch2=make(chan int)
func f1() {
select {
case <- ch1:fmt.Println("ch1")
default: fmt.Println("default")
}
}
func f2() {
select {
case <- ch2:fmt.Println("ch2")
default: fmt.Println("default")
}
}
func w1() {
ch1 <-1
}
func w2() {
ch2 <-1
}
func main() {
var wg sync.WaitGroup
wg.Add(4)
go f1()
go f2()
go w1()
go w2()
wg.Wait()
}
这次错误更多:
default
ch2
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x40e028, 0x0)
/usr/local/go/src/runtime/sema.go:56 +0x40
sync.(*WaitGroup).Wait(0x40e020, 0x14b720)
/usr/local/go/src/sync/waitgroup.go:130 +0x60
main.main()
/tmp/sandbox916639182/prog.go:36 +0x100
goroutine 8 [chan send]:
main.w1()
/tmp/sandbox916639182/prog.go:23 +0x40
created by main.main
/tmp/sandbox916639182/prog.go:34 +0xc0
我哪里出了问题以及如何解决?
幕布斯7119047
慕少森
相关分类