シリーズ: 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()
}
関連記事
Go
go
更新日 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
記事を読む →
Go
go
更新日 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
記事を読む →
Go
go
更新日 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
記事を読む →
Go
go
更新日 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
記事を読む →
Go
go
更新日 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
記事を読む →
Go
go
更新日 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
記事を読む →