工作池模式(提交10个任务给n个goroutine池处理)
package mainimport ("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.WaitGroupfor i := 0; i < 10; i++ {wg.Add(1)task := func() {defer wg.Done()myTask("antsPool", i)}pool.Submit(task)}wg.Wait() }
对象池模式(对象复用)
package mainimport ("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 = 42fmt.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) }