美文网首页
使用Golang sync.Pool节约内存

使用Golang sync.Pool节约内存

作者: FredricZhu | 来源:发表于2019-06-08 20:51 被阅读0次
    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func main() {
        var numCalcsCreated int
        calcPool := &sync.Pool{
            New: func() interface{} {
                numCalcsCreated += 1
                mem := make([]byte, 1024)
                return &mem
            },
        }
    
        //用4kb初始化pool
        calcPool.Put(calcPool.New())
        calcPool.Put(calcPool.New())
        calcPool.Put(calcPool.New())
        calcPool.Put(calcPool.New())
    
        const numWorkers = 1024 * 1024
    
        var wg sync.WaitGroup
        wg.Add(numWorkers)
    
        for i := numWorkers; i > 0; i-- {
            go func() {
                defer wg.Done()
                mem := calcPool.Get().(*[]byte)
                defer calcPool.Put(mem)
            }()
        }
    
        wg.Wait()
    
        fmt.Printf("%d calculators were created.\n", numCalcsCreated)
    }
    
    

    程序输出如下,


    image.png

    相关文章

      网友评论

          本文标题:使用Golang sync.Pool节约内存

          本文链接:https://www.haomeiwen.com/subject/ohlwxctx.html