溫馨提示×

Golang在Linux下的并發編程實踐

小樊
46
2025-08-27 14:26:24
欄目: 編程語言

Golang在Linux下并發編程的核心實踐如下:

  1. Goroutine(輕量級線程)
    go關鍵字啟動并發任務,如go func() { ... }(),由Go運行時調度,支持高并發。
  2. Channel(通道)
    • 用于goroutine間通信,支持同步和數據傳遞,如ch := make(chan int),通過ch <- data發送、<-ch接收。
    • 可創建緩沖通道(make(chan int, capacity))提升效率。
  3. 同步工具
    • WaitGroup:等待一組goroutine完成,通過Add、Done、Wait方法。
    • Mutex:保護共享資源,避免競態條件,如mu.Lock()/mu.Unlock()。
    • RWMutex:支持多讀單寫,提升讀多寫少場景的性能。
  4. Context(上下文控制)
    用于控制goroutine生命周期,如ctx, cancel := context.WithCancel(context.Background()),可主動取消任務。
  5. 注意事項
    • 避免goroutine泄漏,確保通道關閉或任務結束。
    • 閉包中捕獲變量時,需通過參數傳遞避免共享引用問題。

示例代碼(多任務并發+結果收集):

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女