What is go func() {}() and Channel in Go language?

What is go func() {}() and Channel in Go language?

Executes a function using a go statement, which executes a lightweight thread called goroutine.

package main

import (
  "log"
  "time"
)

func main() {
  go func() {
    log.Println("hello")
  }()
  time.Sleep(time.Second) // If I don't sleep, MAIN will exit before the GO statement.
}

What is Channel?

Functions using the go statement are threaded and therefore disappear without execution when main finishes.

By using a messaging called Channel, variables can be sent and received between goroutines.

This Channel can be used for synchronous processing between threads.

The usage of Channel is simple: send is channel<-value and receive is <-channel.

package main

import "log"

func main() {
  fin := make(chan int) // Channel is a reference type, so make() creates an instance
  go func() {
    log.Println("golang")
    fin <- 0 // Send Message
  }()
  log.Println(<-fin) // Block until message received here.
}

Go 言語のgo func() {}()とChannelとは

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL