I am new to golang and trying to understand the concurrency in the language.
Below is a simple code in which I am using channel ch
to communicate with the goroutine say
.
package main
import (
"fmt"
)
func say(ch chan string) {
fmt.Println(<-ch)
ch <- "insinde"
}
func main() {
ch := make(chan string)
go say(ch)
ch <- "first"
fmt.Println(<-ch)
ch <- "second"
fmt.Scan()
}
My expectation from the func main
code is:
- a channel
ch
will be created. - define
say
function as a goroutine. - send
first
value through the channelch
. - which is received by the
say
goroutine. - which in turn will print
first
- and send back
inside
value to the main function. - send another value
second
via channelch
.
but this results in a Deadlock
, could someone highlight why step 7. raise that exception unless go say
is garbage collected before step 7. If that is the case, how can we send another value through the channel.
Cheers,
CodePudding user response:
for no deadlock, make ch buffered : ch := make(chan string, 1)
CodePudding user response:
In func main,second send value to chan is blocked