Golang在Linux下并发编程的核心实践如下:
go关键字启动并发任务,如go func() { ... }(),由Go运行时调度,支持高并发。ch := make(chan int),通过ch <- data发送、<-ch接收。make(chan int, capacity))提升效率。Add、Done、Wait方法。mu.Lock()/mu.Unlock()。ctx, cancel := context.WithCancel(context.Background()),可主动取消任务。示例代码(多任务并发+结果收集):
package main
import (
"fmt"
"sync"
)
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
results <- job * 2 // 处理任务并返回结果
}
}
func main() {
jobs := make(chan int, 10)
results := make(chan int, 10)
var wg sync.WaitGroup
// 启动3个worker
for w := 1; w <= 3; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
// 发送任务
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// 等待所有worker完成
wg.Wait()
close(results)
// 输出结果
for res := range results {
fmt.Println("Result:", res)
}
}