package main
import (
"context"
"encoding/json"
"fmt"
"os"
"reflect"
"runtime"
"sort"
"sync"
)
type Case struct {
Name string `json:"name"`
Summary string `json:"summary"`
Expected any `json:"expected"`
Actual any `json:"actual"`
Passed bool `json:"passed"`
}
type Report struct {
Version string `json:"version"`
Cases []Case `json:"cases"`
}
func makeCase(name, summary string, expected, actual any) Case {
return Case{
Name: name,
Summary: summary,
Expected: expected,
Actual: actual,
Passed: reflect.DeepEqual(expected, actual),
}
}
func partialSum(s []int, c chan<- int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum
}
func fibToChan(n int, c chan<- int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func fibSelect(c chan<- int, quit <-chan struct{}, exited chan<- bool) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
exited <- true
return
}
}
}
func main() {
var cases []Case
// Case 1: Goroutines + unbuffered channel sum
s := []int{7, 2, 8, -9, 4, 0}
sumCh := make(chan int)
go partialSum(s[:len(s)/2], sumCh)
go partialSum(s[len(s)/2:], sumCh)
x, y := <-sumCh, <-sumCh
parts := []int{x, y}
sort.Ints(parts)
actual1 := map[string]any{
"sorted_parts": parts,
"total": x + y,
}
expected1 := map[string]any{
"sorted_parts": []int{-5, 17},
"total": 12,
}
cases = append(cases, makeCase(
"goroutine_and_unbuffered_channel",
"核对双 goroutine 分段求和并通过无缓冲通道同步汇总结果",
expected1, actual1,
))
// Case 2: Buffered channel + close + range traversal
bufCh := make(chan int, 2)
bufCh <- 1
bufCh <- 2
b1 := <-bufCh
b2 := <-bufCh
fibCh := make(chan int, 10)
go fibToChan(cap(fibCh), fibCh)
var fibVals []int
for v := range fibCh {
fibVals = append(fibVals, v)
}
closedVal, closedOk := <-fibCh
actual2 := map[string]any{
"buffered_reads": []int{b1, b2},
"fib_10": fibVals,
"after_close_v": closedVal,
"after_close_ok": closedOk,
}
expected2 := map[string]any{
"buffered_reads": []int{1, 2},
"fib_10": []int{0, 1, 1, 2, 3, 5, 8, 13, 21, 34},
"after_close_v": 0,
"after_close_ok": false,
}
cases = append(cases, makeCase(
"buffered_channel_and_range_close",
"核对带缓冲通道异步收发、range 遍历直至 close(ch) 及关闭后 comma-ok 返回 false",
expected2, actual2,
))
// Case 3: select multiplexing with explicit quit signal
selCh := make(chan int)
quitCh := make(chan struct{})
exitedCh := make(chan bool, 1)
go fibSelect(selCh, quitCh, exitedCh)
selVals := make([]int, 0, 10)
for i := 0; i < 10; i++ {
selVals = append(selVals, <-selCh)
}
close(quitCh)
didExit := <-exitedCh
actual3 := map[string]any{
"select_fib": selVals,
"exited": didExit,
}
expected3 := map[string]any{
"select_fib": []int{0, 1, 1, 2, 3, 5, 8, 13, 21, 34},
"exited": true,
}
cases = append(cases, makeCase(
"select_multiplex_and_quit",
"核对 select 多路复用通道发送与 quit 退出信号确定性终止协程",
expected3, actual3,
))
// Case 4: sync.WaitGroup deterministic worker coordination
var wg sync.WaitGroup
results := make([]string, 3)
for i := 0; i < 3; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
results[idx] = fmt.Sprintf("worker-%d-done", idx+1)
}(i)
}
wg.Wait()
actual4 := map[string]any{
"worker_results": results,
}
expected4 := map[string]any{
"worker_results": []string{"worker-1-done", "worker-2-done", "worker-3-done"},
}
cases = append(cases, makeCase(
"sync_waitgroup_coordination",
"核对 sync.WaitGroup 的 Add/Done/Wait 协调多 goroutine 全部完成后再汇总",
expected4, actual4,
))
// Case 5: sync.Mutex concurrency safety & context.WithCancel lifecycle
var mu sync.Mutex
counter := 0
var cwg sync.WaitGroup
for g := 0; g < 8; g++ {
cwg.Add(1)
go func() {
defer cwg.Done()
for j := 0; j < 500; j++ {
mu.Lock()
counter++
mu.Unlock()
}
}()
}
cwg.Wait()
ctx, cancel := context.WithCancel(context.Background())
started := make(chan struct{})
stopped := make(chan string, 1)
go func() {
close(started)
<-ctx.Done()
stopped <- ctx.Err().Error()
}()
<-started
cancel()
cancelReason := <-stopped
actual5 := map[string]any{
"mutex_counter": counter,
"cancel_reason": cancelReason,
}
expected5 := map[string]any{
"mutex_counter": 4000,
"cancel_reason": "context canceled",
}
cases = append(cases, makeCase(
"mutex_rwmutex_and_context_cancel",
"核对 sync.Mutex 保护共享计数器消除数据竞争及 context.WithCancel 精确取消协程",
expected5, actual5,
))
report := Report{
Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
Cases: cases,
}
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(report); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
本例需在 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。
入口文件:projects/go-concurrent-lab/explore_concurrent.go
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore_concurrent.go,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1161.zip