好好爱自己!

golang sync.pool

 

 

这个例子,理解一下

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
 
import (
    "fmt"
    "sync"
    "time"
)
 
// Pool for our struct A
var pool *sync.Pool
 
// A dummy struct with a member
type A struct {
    Name string
}
 
// Func to init pool
func initPool() {
    pool = &sync.Pool {
        New: func()interface{} {
            fmt.Println("Returning new A")
            return new(A)
        },
    }
}
 
// Main func
func main() {
    // Initializing pool
    initPool()
    // Get hold of instance one
    one := pool.Get().(*A)
    one.Name = "first"
    fmt.Printf("one.Name = %s\n", one.Name)
    // Pass one to a go routine that just stops for 10 second
    // Assume that this could be any i/o bound task, something like an API call
    go func(o *A) {
        fmt.Printf("Before pool.Put\no.Name = %s\n", o.Name)
        time.Sleep(10 * time.Second)
        fmt.Printf("After pool.Put With same object\no.Name = %s\n", o.Name)
    }(one)
    // Main routine performs some operations for 1 second
    time.Sleep(1 * time.Second)
    // Till then your main routine submits back the main object
    pool.Put(one)
    two := pool.Get().(*A)
    two.Name = "second"
    fmt.Printf("two.Name = %s\n", two.Name)
    // Just for the sake of demo wait for next 15 seconds
    time.Sleep(15 * time.Second)   
}

  

 

posted @   立志做一个好的程序员  阅读(94)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2018-09-30 es6中的import,export浏览器已经支持
2016-09-30 Jquery 源码学习
2016-09-30 php 中的魔术方法-----“事件方法”
2016-09-30 php 语法中有 let 吗?

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示