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)
}
}