Home > Software engineering >  Go: Concurrency and channel understanding
Go: Concurrency and channel understanding

Time:08-28

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:

  1. a channel ch will be created.
  2. define say function as a goroutine.
  3. send first value through the channel ch.
  4. which is received by the say goroutine.
  5. which in turn will print first
  6. and send back inside value to the main function.
  7. send another value second via channel ch.

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

  • Related