I have this piece of Go code. I need to have this ability: write into channels in one place, and read them out in another place(or vice versa):
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
}
It always prints sth like this:
default
ch1
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox970110849/prog.go:22 +0xa0
Further more I tried this:
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()
}
Even more errors this time:
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
Where did I go wrong and how to fix it?