github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/bfs/gzip_reader_pool.go (about) 1 // Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package bfs 4 5 import ( 6 "github.com/TeaOSLab/EdgeNode/internal/utils/percpu" 7 "github.com/klauspost/compress/gzip" 8 "io" 9 "runtime" 10 ) 11 12 var SharedDecompressPool = NewGzipReaderPool() 13 14 type GzipReaderPool struct { 15 c chan *gzip.Reader 16 cList []chan *gzip.Reader 17 } 18 19 func NewGzipReaderPool() *GzipReaderPool { 20 const poolSize = 16 21 22 var countProcs = runtime.GOMAXPROCS(0) 23 if countProcs <= 0 { 24 countProcs = runtime.NumCPU() 25 } 26 countProcs *= 4 27 28 var cList []chan *gzip.Reader 29 for i := 0; i < countProcs; i++ { 30 cList = append(cList, make(chan *gzip.Reader, poolSize)) 31 } 32 33 return &GzipReaderPool{ 34 c: make(chan *gzip.Reader, poolSize), 35 cList: cList, 36 } 37 } 38 39 func (this *GzipReaderPool) Get(rawReader io.Reader) (*gzip.Reader, error) { 40 select { 41 case w := <-this.getC(): 42 err := w.Reset(rawReader) 43 if err != nil { 44 return nil, err 45 } 46 return w, nil 47 default: 48 return gzip.NewReader(rawReader) 49 } 50 } 51 52 func (this *GzipReaderPool) Put(reader *gzip.Reader) { 53 select { 54 case this.getC() <- reader: 55 default: 56 // 不需要close,因为已经在使用的时候调用了 57 } 58 } 59 60 func (this *GzipReaderPool) getC() chan *gzip.Reader { 61 var procId = percpu.GetProcId() 62 if procId < len(this.cList) { 63 return this.cList[procId] 64 } 65 return this.c 66 }