Channels

  • Communicate data between Goroutines
  • Synchronise Goroutines
  • Typed
  • Thread-safe

Declare and Initialize

var ch chan T
ch = make(chan T)

or

ch := make(chan T)

<- operator

Send value: ch<-v Receive value: v=<-ch

Channels are blocking

ch<-v Goroutine wait for a reciever to be ready. <-ch Goroutine wait for a value to be sent.

Close(ch)

  • No more value to be sent.
  • value,ok = <-ch
    • ok == true . value generated by a write.
    • ok == false . value generated by a close.

https://go.dev/play/p/V011cxbMS_-

package main

import "fmt"

func main() {
    ch := make(chan int)

    go func(a, b int) {
        c := a + b
        ch <- c
    }(1, 2)
    // get the value computed from goroutine
    c := <-ch
    fmt.Printf("computed value %v\n", c)
}
© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""