在CentOS上使用Go语言并发功能前,需先完成Go的安装及环境变量配置。通过yum安装Go后,编辑/etc/profile文件添加export PATH=$PATH:/usr/local/go/bin(替换为实际安装路径),并执行source /etc/profile使配置生效,确保终端可直接使用go命令。
GOMAXPROCS是控制Go程序并发执行的关键参数,它决定了同时运行的操作系统线程(M)的最大数量,直接影响多核CPU的利用率。
runtime.NumCPU()获取)。export GOMAXPROCS=4(Linux/Mac)或set GOMAXPROCS=4(Windows)设置,优先级高于代码方式。runtime.GOMAXPROCS(4)设置(若值为0则返回当前值,不修改)。-e GOMAXPROCS=4(运行时指定)或在Dockerfile中ENV GOMAXPROCS=4设置,匹配容器可用的逻辑核心数。WorkerPool)限制并发数量,复用Goroutine减少创建/销毁开销。sync.WaitGroup等待一组Goroutine完成。通过wg.Add(1)(启动前增加计数)、defer wg.Done()(完成后减少计数)、wg.Wait()(主程序等待)确保所有任务结束。sync.Mutex保护共享资源(如全局变量),避免并发访问冲突。例如:var mu sync.Mutex var counter int func increment() { mu.Lock() defer mu.Unlock() counter++ } sync.RWMutex允许多个读操作并发执行,写操作独占,提升读性能。sync.Once确保某段代码仅执行一次(如初始化配置),避免重复初始化。make(chan int, bufferSize)创建缓冲通道(如bufferSize=10),减少Goroutine间的阻塞(无缓冲通道需发送/接收双方就绪)。例如:ch := make(chan int, 10) go func() { for i := 0; i < 10; i++ { ch <- i } close(ch) }() for num := range ch { fmt.Println(num) } 通过WorkerPool模式限制并发Goroutine数量,避免资源耗尽。示例代码:
type Job struct { Data string } type Result struct { Result string } type WorkerPool struct { Work chan Job Wg sync.WaitGroup } func NewWorkerPool(size int) *WorkerPool { return &WorkerPool{ Work: make(chan Job), Wg: sync.WaitGroup{}, } } func (wp *WorkerPool) Run() { for i := 0; i < cap(wp.Work); i++ { go func() { for job := range wp.Work { // 处理任务(如调用process(job)) wp.Wg.Done() } }() } } func (wp *WorkerPool) Submit(job Job) { wp.Wg.Add(1) wp.Work <- job } func main() { pool := NewWorkerPool(3) // 限制3个并发Goroutine pool.Run() for i := 0; i < 10; i++ { pool.Submit(Job{Data: fmt.Sprintf("Task-%d", i)}) } pool.Wg.Wait() // 等待所有任务完成 } net/http/pprof包开启性能分析,通过go tool pprof http://localhost:6060/debug/pprof/profile(CPU分析)或go tool pprof http://localhost:6060/debug/pprof/heap(内存分析)识别瓶颈(如CPU占用高的函数、内存泄漏)。runtime/trace包记录程序执行轨迹,分析Goroutine调度、阻塞等情况,识别并发问题(如死锁、Goroutine泄漏)。使用context包实现超时控制和任务取消,避免Goroutine长时间阻塞。例如:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() select { case result := <-ch: fmt.Println("Result:", result) case <-ctx.Done(): fmt.Println("Timeout or canceled") } var cache sync.Map cache.Store("key", "value") if value, ok := cache.Load("key"); ok { fmt.Println(value) } redis(缓存)、gorm(数据库连接池)等并发安全库,减少自行实现同步逻辑的复杂度。sync.Once确保初始化只执行一次。sync.Pool复用对象(如数据库连接、临时缓冲区),降低垃圾回收(GC)频率;预分配切片/映射容量(如make([]int, 0, 100)),避免动态扩容。net.ipv4.tcp_tw_reuse=1禁用TIME_WAIT状态、net.core.rmem_max=16777216增加接收缓冲区大小),提升网络传输效率。Gin(HTTP框架)、Redis(缓存)等高性能库,减少框架本身的性能开销。