linux

Golang在Linux下的并发编程实践

小樊
50
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完成,通过AddDoneWait方法。
    • 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
看了该问题的人还看了