Communication b/w Go Routines in Go

Communication b/w Go Routines in Go

GoRoutine :- A GoRoutine is a light weight thread message by the go Runtime and makes application stays responsive and faster.

Different goroutines communicate in Golang, or Go using channels ,Channels are a means through which communication happens.

It is a pipe like connection by which you can connect with different go routines, It is a two way communication so that you can send and recieve values from the same channel

Process for creating a channel

  1. make(chan[value-type]) -- value type indicate the data type eg: int

  2. channel < - sending the value to channel

  3. < - channel recieve the value from the channel

  4. close(channel) closing the channel.

Sample scenario with Illustration:

package main

import "fmt"

// Prints a FirstName message using values received in the channel

func  getName(c chan string) {

    fname := <-c // receiving value from channel
    fmt.Println("Hello", fname)
}

func main() {

    // creates a channel with value type string to pass the fname
    c := make(chan string)

    //  goroutine
    go getName(c)   

    // Sending values the information  to the channel c
    c <- "Ashok"

    // Closing channel
    close(c)
}