golang优化

工作池模式(提交10个任务给n个goroutine池处理)

package main

import (
    "fmt"
    "sync"
    "time"

    "github.com/panjf2000/ants"
)

// 模拟一个需要被处理的任务
func myTask(callName string, i int) {
    time.Sleep(100 * time.Millisecond) // 模拟任务处理耗时
    fmt.Printf("%s processing task %d\n", callName, i)
}

func main() {
    // 普通goroutine写法,创建10个goroutine处理任务
    for i := 0; i < 10; i++ {
        go func() {
            myTask("goroutine", i)
        }()
    }

    // 提交10个任务给n个goroutine池处理
    pool, err := ants.NewPool(5) // 创建固定大小的ants池(n个goroutine)
    if err != nil {
        fmt.Printf("Failed to create pool: %v\n", err)
        return
    }
    defer pool.Release()
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        task := func() {
            defer wg.Done()
            myTask("antsPool", i)
        }
        pool.Submit(task)
    }
    wg.Wait()
}

对象池模式(对象复用)

package main

import (
    "bytes"
    "fmt"
    "sync"
)

type Data struct {
    Value int
}

func createData() *Data {
    return &Data{Value: 42}
}

var dataPool = sync.Pool{
    New: func() any {
        return &Data{}
    },
}

var bufferPool = sync.Pool{
    New: func() any {
        return new(bytes.Buffer)
    },
}

func main() {
    for i := 0; i < 10; i++ {
        // 普通对象初始化
        obj1 := createData()
        fmt.Println(obj1.Value)

        // 使用对象池化 -- sync.Pool,使用场景:短期存活、可复用对象
        obj2 := dataPool.Get().(*Data)
        obj2.Value = 42
        fmt.Println(obj2.Value)
        dataPool.Put(obj2)
    }

    // 池化字节缓冲区
    buf := bufferPool.Get().(*bytes.Buffer)
    buf.Reset()
    buf.WriteString("Hello, pooled world!")
    fmt.Println(buf.String())
    bufferPool.Put(buf)
}

 

posted @ 2025-10-14 08:40  CHHC  阅读(6)  评论(0)    收藏  举报