Go goroutine and channel

go routine

Go routine is golang lightweight parallel process function.

Run function asynchronously.

Example

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	go func() {
		fmt.Println("Goroutine")
		os.Exit(0) // finish
	}()

	time.Sleep(time.Duration(3) * time.Second)
	fmt.Println("End")
}

Run func using go prefix. Main thread does not wait go routine to finish. In this program, os.Exit(0) finish and back to main.

Channel

To communicate values between goroutine, use channel.

This is an easy example

package main

import (
	"fmt"
)

func main() {
	//channel := make(chan int) // Create channel
	channel2 := make(chan string)
	/*
		go func(s chan<- int) {
			for i := 0; i < 10; i++ {
				s <- i
			}
			close(s)
		}(channel)*/

	go func(s chan<- string) {
		for i := 0; i < 10; i++ {
			s <- fmt.Sprintf("%d %s", i, "Hello")
		}
		close(s)
	}(channel2)

	for { // wait
		//	value, ok := <-channel
		value, ok := <-channel2

		if !ok {
			break // finish
		}
		fmt.Println(value)
	}
}
golang
スポンサーリンク
Professional Programmer2

コメント