当前位置:网站首页>[golang] follow the object pool sync Pool
[golang] follow the object pool sync Pool
2022-06-23 20:05:00 【DDGarfield】
Learn some skills in the source code
1. from Run() Start
stay go Linguistic gin In the frame , adopt .Run() start-up web service . Let's look at the source code :
//gin.go
func (engine *Engine) Run(addr ...string) (err error) {
defer func() { debugPrintError(err) }()
address := resolveAddress(addr)
debugPrint("Listening and serving HTTP on %s\n", address)
err = http.ListenAndServe(address, engine)
return
}
among ListenAndServe yes net/http The listening address and processor specified in the library
//net/http/server.go
func ListenAndServe(addr string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
You can see gin What is called in the source code is engine *Engine As Handler Parameters , Continue to check Handler Source code :
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
indeed Handler It's an interface , Interface method :ServeHTTP(ResponseWriter, *Request)
that Engine It must have come true **ServeHTTP** Method
adopt VSCode Navigation , I did Engine The struct implements this method :
// ServeHTTP conforms to the http.Handler interface.
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
c := engine.pool.Get().(*Context)
c.writermem.reset(w)
c.Request = req
c.reset()
engine.handleHTTPRequest(c)
engine.pool.Put(c)
}
2.sync.Pool On stage
Let's look at the third line of code in the previous section :
c := engine.pool.Get().(*Context)
type Engine struct {
//omit code
pool sync.Pool
}
among pool The fields are sync.Pool type , What is that sync.Pool?
original : This is a go The concept of a typical object pool in a language , In order to reduce the GC, Reduce the frequency of memory requests , Construct a pool of reusable objects ,engine.pool.Get() Is to take an object out of the pool , Cast to context The pointer .
- Through the object pool , Reduce the consumption of memory application and garbage collection for each temporary object creation
- Frequent object application and recycling , You can use object pooling to optimize your code
- It can avoid object reference or other interference , Without affecting the actual function of the code , After an object is removed from the pool , Then do initialization
3. Usage method
sync.Pool It's very simple to use :
3.1 Statement
//gin.go
func New() *Engine {
debugPrintWARNINGNew()
engine := &Engine{
RouterGroup: RouterGroup{
Handlers: nil,
basePath: "/",
root: true,
},
FuncMap: template.FuncMap{},
RedirectTrailingSlash: true,
RedirectFixedPath: false,
HandleMethodNotAllowed: false,
ForwardedByClientIP: true,
AppEngine: defaultAppEngine,
UseRawPath: false,
RemoveExtraSlash: false,
UnescapePathValues: true,
MaxMultipartMemory: defaultMultipartMemory,
trees: make(methodTrees, 0, 9),
delims: render.Delims{Left: "{{", Right: "}}"},
secureJsonPrefix: "while(1);",
}
engine.RouterGroup.engine = engine
// Realization New function
engine.pool.New = func() interface{} {
return engine.allocateContext()
}
return engine
}
- Just implement New Function . When there are no objects in the object pool , Will call
NewFunction creation .
3.2 Get()
obtain
Get()Used to get objects from the object pool , Because the return value isinterface{}, Therefore, type conversion is required , The above code has been shown .
c := engine.pool.Get().(*Context)
3.3 Put()
Put back
Put()After the object is used , Return object pool .
processed http After the request , Also put context Put back into the object pool :
engine.handleHTTPRequest(c)
engine.pool.Put(c)
3. matters needing attention
sync.Pool It's scalable , Concurrent security . Its size is limited only by the size of memory , It can be seen as a container for storing the values of reusable objects . It is designed to Store allocated but temporarily unused objects , When you need it, you can get it directly from pool To take . Values in any store can be deleted at any time without notice , It can be dynamically expanded under high load , When inactive, the object pool shrinks .
Because of the bold font above , So the object pool is more suitable for storing some temporary state independent data , Because the values stored in the object pool may be deleted during garbage collection .http Requested context Context is such a type .
4. Add another technique
stay gin The source code defines Engine There is a sentence at the bottom of the structure :
var _ IRouter = &Engine{}
An obscure anonymous variable : Anonymous variables don't take up memory space , Memory will not be allocated , What's the use of it ? It can't be that the author forgot , Such a famous open source library .
original go Languages often encounter a scenario , After writing a structure , This structure implements many interfaces , The problem is , After the code is complicated , Who can still remember which interface is implemented or not , What do I do ?
- Manual inspection , Um. , It's a way ,
Ctrl+Fcomparison , Find the method receiver , Um. , It's also a way
however , A better way , It depends on the compiler :
Define an anonymous variable var _ Interface type = Structure type pointer , This is mainly to ensure that the structure does implement the interface , The purpose is to Expose the problem in the compilation phase , Many third-party libraries and standard libraries do this , Worth learning .
Reference link
https://www.cnblogs.com/sunsky303/p/9706210.html
https://geektutu.com/post/hpg-sync-pool.html
------------------- End -------------------
边栏推荐
- 35歲危機?內卷成程序員代名詞了…
- Technology sharing | wvp+zlmediakit realizes streaming playback of camera gb28181
- Shell Scripting
- 打新债有条件吗 打新债安全吗
- 重庆 奉节耀奎塔,建成后当地连中五名进士,是川江航运的安全塔
- Stochastic process -- Markov chain
- MySQL时间函数的运用,简单问题
- FPGA based electromagnetic ultrasonic pulse compression detection system paper + source file
- 测试的重要性及目的
- 深入理解和把握数字经济的基本特征
猜你喜欢

Zabbix监控- Aruba AP运行数据

「开源摘星计划」Containerd拉取Harbor中的私有镜像,云原生进阶必备技能

Check four WiFi encryption standards: WEP, WPA, WPA2 and WPA3

ZABBIX monitoring - Aruba AP operation data

SAVE: 软件分析验证和测试平台

Hotline salon issue 26 - cloud security session

Rstudio 1.4 software installation package and installation tutorial

好用的人事管理软件有哪些?人事管理系统软件排名!

Development notes of wedding studio applet based on wechat applet

Daily question brushing record (II)
随机推荐
Check four WiFi encryption standards: WEP, WPA, WPA2 and WPA3
OHOS LTS 3.0移植到RaspberryPi 4B
徽商期货交易软件正规吗?如何安全下载?
Interpreting the 2022 agile coaching industry status report
Yaokui tower in Fengjie, Chongqing, after its completion, will be the safety tower for Sichuan river shipping with five local scholars in the company
【Golang】深究字符串——从byte rune string到Unicode与UTF-8
科班出身,结果外包都不要
Uniswap founder: no independent token will be issued for genie, and Genie products will be integrated into the uniswap interface
Live sharing | Tencent cloud mongodb intelligent diagnosis and Performance Optimization Practice
直播分享| 腾讯云 MongoDB 智能诊断及性能优化实践
Idea console displays Chinese garbled code
How to use data warehouse to create time series
LeetCode 473. 火柴拼正方形
想开个户,在股票网上开户安全吗?资金会被骗走吗?
UGeek大咖说 | 可观测之超融合存储系统的应用与设计
官宣.NET 7 预览版5
怎么开户?在国海证券开户安全吗?需要带什么?
Shell Scripting
Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage
【Golang】怎样优雅的清空切片