I want to print 1 to 100 use two goroutine:
package main
import (
"fmt"
"sync"
)
var my_chan chan int
var wg sync.WaitGroup
func worker() {
for true {
number := <-my_chan
fmt.Println(number)
number
if number > 100 {
wg.Done()
return
}
my_chan <- number
}
}
func main() {
wg.Add(2)
my_chan := make(chan int)
init_num := 1
go worker()
go worker()
my_chan <- init_num
wg.Wait()
}
When I run the above code, I get the following error:
fatal error: all goroutines are asleep - deadlock!
Can anyone tell me where I am doing wrong?
CodePudding user response:
Replace the channel creation with this:
my_chan = make(chan int)
Otherwise you are redeclaring my_chan
in main, and all goroutines try to read from a nil channel. That will block.
Then it will count to 100 and deadlock. The check for number being larger than 100 will work for one of the goroutines, while the other one will be stuck waiting to read/write.
CodePudding user response:
Thanks for Burak Serdar's answer, the following code works:
package main
import (
"fmt"
"sync"
)
var my_chan chan int
var wg sync.WaitGroup
func worker() {
for true {
number := <-my_chan
if number > 100 {
wg.Done()
my_chan <- 101
return
}
fmt.Println(number)
number
my_chan <- number
}
}
func main() {
wg.Add(2)
my_chan = make(chan int)
init_num := 1
go worker()
go worker()
my_chan <- init_num
wg.Wait()
}