本文整理匯總了Golang中sync.Pool.New方法的典型用法代碼示例。如果您正苦於以下問題:Golang Pool.New方法的具體用法?Golang Pool.New怎麽用?Golang Pool.New使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sync.Pool
的用法示例。
在下文中一共展示了Pool.New方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
_, err := OutFunc()
if err != nil {
log.Printf("error is : %v", err)
}
fmt.Printf("End of main")
data := []int{0, 1, 2, 3, 4}
s1 := data[:2]
fmt.Printf("data ptr is %p, s1 ptr is %p", &data, &s1)
s2 := append(s1, 100, 200)
fmt.Println("\n", data)
fmt.Println(s1)
fmt.Println(s2)
fmt.Printf("data ptr is %p, s1 ptr is %p, s2 ptr is %p \n", &data, &s1, &s2)
var pool *sync.Pool
pool = new(sync.Pool)
pool.New = func() interface{} {
return 1
}
//pool.Put(1)
i := pool.Get()
if i == nil {
fmt.Println("pool.Get is non-block function. nil could be returned. not cool")
} else {
fmt.Println("number is ", i)
}
}
示例2: main
func main() {
// 禁用GC,並保證在main函數執行結束前恢複GC
defer debug.SetGCPercent(debug.SetGCPercent(-1))
var count int32
newFunc := func() interface{} {
return atomic.AddInt32(&count, 1)
}
pool := sync.Pool{New: newFunc}
// New 字段值的作用
v1 := pool.Get()
fmt.Printf("v1: %v\n", v1)
// 臨時對象池的存取
pool.Put(newFunc())
pool.Put(newFunc())
pool.Put(newFunc())
v2 := pool.Get()
fmt.Printf("v2: %v\n", v2)
// 垃圾回收對臨時對象池的影響
debug.SetGCPercent(100)
runtime.GC()
v3 := pool.Get()
fmt.Printf("v3: %v\n", v3)
pool.New = nil
v4 := pool.Get()
fmt.Printf("v4: %v\n", v4)
}
示例3: Gzip
func Gzip(level int) gin.HandlerFunc {
var gzPool sync.Pool
gzPool.New = func() interface{} {
gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
if err != nil {
panic(err)
}
return gz
}
return func(c *gin.Context) {
if !shouldCompress(c.Request) {
return
}
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(c.Writer)
c.Header("Content-Encoding", "gzip")
c.Header("Vary", "Accept-Encoding")
c.Writer = &gzipWriter{c.Writer, gz}
defer func() {
c.Header("Content-Length", "0")
gz.Close()
}()
c.Next()
}
}
示例4: NewByteSlicePool
func NewByteSlicePool(size int) *ByteSlicePool {
p := new(sync.Pool)
p.New = func() interface{} {
return make([]byte, size)
}
return &ByteSlicePool{p}
}
示例5: newBufferPool
func newBufferPool() *bufferPool {
var p sync.Pool
p.New = func() interface{} {
return make([]byte, 20480)
}
return &bufferPool{p}
}
示例6: NewMPool
func NewMPool(sz int) *MPool {
p := &MPool{sz: sz}
pool := new(sync.Pool)
pool.New = func() interface{} {
buf := make([]byte, p.sz)
atomic.AddInt32(&p.alloced, 1)
return buf
}
p.pool = pool
return p
}
示例7: main
func main() {
var pool sync.Pool
pool.New = func() interface{} {
return person{name: "name", timestamp: time.Now()}
}
var p, q, r person
p = pool.Get().(person)
fmt.Println(p.timestamp.String())
pool.Put(p)
r = pool.Get().(person)
q = pool.Get().(person)
fmt.Println(r.timestamp.String())
fmt.Println(q.timestamp.String())
}
示例8: test1
func test1() {
//Pool內存緩存 GC時將被清除
var bp sync.Pool
var looks sync.RWMutex
bp.New = func() interface{} {
return &bytes.Buffer{}
}
buf := bp.Get().(*bytes.Buffer)
buf.WriteString("test")
fmt.Println(buf.String())
bp.Put(buf) //記錄至緩存
limit := make(chan struct{}, 10)
go func() {
buf := bp.Get().(*bytes.Buffer)
buf.WriteString("tttt")
looks.Lock()
bp.Put(buf)
looks.Unlock()
}()
time.Sleep(1 * time.Second)
for {
limit <- struct{}{}
go func() {
//提取以後必須再次Put 否則將被清除
buf := bp.Get().(*bytes.Buffer)
if buf.Len() != 0 {
fmt.Println(buf.String())
looks.Lock()
bp.Put(buf)
looks.Unlock()
//runtime.GC()
}
<-limit
}()
}
return
runtime.GC() //手動啟動GC
buf = bp.Get().(*bytes.Buffer) //由於緩存被清空 反問內容為空
fmt.Println(buf.String())
}
示例9: Gzip
// Handle provides on-the-fly gzip encoding for other handlers.
//
// Usage:
//
// func DL1Handler(w http.ResponseWriter, req *http.Request) {
// fmt.Fprintln(w, "foobar")
// }
//
// func DL2Handler(w http.ResponseWriter, req *http.Request) {
// fmt.Fprintln(w, "zzz")
// }
//
//
// func main() {
// http.HandleFunc("/download1", DL1Handler)
// http.HandleFunc("/download2", DL2Handler)
// http.ListenAndServe(":8080", Gzip(http.DefaultServeMux))
// }
func Gzip(h http.Handler) http.HandlerFunc {
var pool sync.Pool
pool.New = func() interface{} {
return gzip.NewWriter(ioutil.Discard)
}
return func(w http.ResponseWriter, r *http.Request) {
// Do nothing on a HEAD request
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") || r.Method == "HEAD" ||
w.Header().Get("Content-Encoding") == "gzip" { // Skip compression if already compressed
h.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := pool.Get().(*gzip.Writer)
defer pool.Put(gz)
gz.Reset(w)
h.ServeHTTP(IOResponseWriter{Writer: gz, ResponseWriter: WrapWriter(w)}, r)
gz.Close()
}
}
示例10: GenSetPool
func (sn *Node) GenSetPool() {
var p sync.Pool
p.New = NewSigningMessage
sn.SetPool(&p)
}
示例11: startHTTPServer
func startHTTPServer(hostport string, msgchs []chan<- msg, quit <-chan struct{}, wg *sync.WaitGroup) {
var bufPool sync.Pool
var msgPool sync.Pool
msgPool.New = func() interface{} {
return &msg{nil, make(chan error, 1)}
}
var rndPool sync.Pool
rndPool.New = func() interface{} {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}
handler := func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
cl := int(r.ContentLength)
if cl <= 0 {
http.Error(w, http.StatusText(http.StatusLengthRequired), http.StatusLengthRequired)
return
}
buf, ok := bufPool.Get().([]byte)
if ok && cap(buf) < cl+16 { // + 16, in case of worker will need to encode object
bufPool.Put(buf)
buf = make([]byte, cl, cl+16)
} else if ok {
buf = buf[:cl]
} else {
buf = make([]byte, cl, cl+16)
}
defer bufPool.Put(buf)
if _, err := io.ReadFull(r.Body, buf); err != nil {
log.Println("HTTP server: failed to read body", err)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
msg := msgPool.Get().(*msg)
defer msgPool.Put(msg)
msg.buf = buf
rnd := rndPool.Get().(*rand.Rand)
defer rndPool.Put(rnd)
msgchs[rnd.Intn(len(msgchs))] <- *msg
if err := <-msg.err; err != nil {
log.Println("HTTP server: failed to process message", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
addr, err := net.ResolveTCPAddr("tcp4", hostport)
if err != nil {
log.Fatal("failed to resolve addr: ", err)
}
conn, err := net.ListenTCP("tcp4", addr)
if err != nil {
log.Fatal("failed to lister UDP socket: ", err)
}
http.HandleFunc("/", handler)
srv := &http.Server{Addr: hostport}
go func() {
log.Println("starting HTTP server", hostport)
wg.Add(1)
defer wg.Done()
srv.Serve(newStoppableListener(conn, quit))
}()
}