S SmartDocs
シリーズ: Go go 80 行 · 更新日 2026-04-18

main.go

Go/part1-language/examples/10_concurrency/main.go

// Demonstrates goroutines, channels, select, WaitGroup, context, pipelines.
package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

func gen(nums ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, n := range nums {
			out <- n
		}
	}()
	return out
}

func square(in <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for v := range in {
			out <- v * v
		}
	}()
	return out
}

func waitGroupDemo() {
	var wg sync.WaitGroup
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			fmt.Println("worker", i, "done")
		}(i)
	}
	wg.Wait()
}

func contextDemo() {
	ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel()

	select {
	case <-time.After(time.Second):
		fmt.Println("slow op done")
	case <-ctx.Done():
		fmt.Println("aborted:", ctx.Err())
	}
}

func selectDemo() {
	a := make(chan string, 1)
	b := make(chan string, 1)
	go func() { time.Sleep(50 * time.Millisecond); a <- "from a" }()
	go func() { time.Sleep(20 * time.Millisecond); b <- "from b" }()

	for i := 0; i < 2; i++ {
		select {
		case m := <-a:
			fmt.Println("got", m)
		case m := <-b:
			fmt.Println("got", m)
		}
	}
}

func main() {
	for v := range square(gen(1, 2, 3, 4, 5)) {
		fmt.Println("square:", v)
	}
	waitGroupDemo()
	selectDemo()
	contextDemo()
}

関連記事