偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

Golang中Sync.Pool詳解及使用方法

開(kāi)發(fā) 前端
在Golang的很多標(biāo)準(zhǔn)庫(kù)和很多知名的開(kāi)源庫(kù)中,都可以看到大量使用sync.Pool的場(chǎng)景。例如encoding/json包中的Valid方法使用sync.Pool創(chuàng)建scanner對(duì)象,Gin框架使用sync.Pool來(lái)復(fù)用每個(gè)請(qǐng)求都會(huì)創(chuàng)建的gin.Context對(duì)象。

什么是sync.Pool?

sync.Pool是用來(lái)保存可以被重復(fù)使用的臨時(shí)對(duì)象,以便在以后的同類操作中可以重復(fù)使用,從而避免了反復(fù)創(chuàng)建和銷毀臨時(shí)對(duì)象帶來(lái)的消耗以及對(duì)GC造成的壓力。常用池化技術(shù)來(lái)提高程序的性能,例如連接池、線程池等。sync.Pool是并發(fā)安全的,可以在多個(gè)goroutine中并發(fā)調(diào)用sync.Pool存取對(duì)象。

在Golang的很多標(biāo)準(zhǔn)庫(kù)和很多知名的開(kāi)源庫(kù)中,都可以看到大量使用sync.Pool的場(chǎng)景。例如encoding/json包中的Valid方法使用sync.Pool創(chuàng)建scanner對(duì)象,Gin框架使用sync.Pool來(lái)復(fù)用每個(gè)請(qǐng)求都會(huì)創(chuàng)建的gin.Context對(duì)象。

但需要注意的是,sync.Pool保存的對(duì)象隨時(shí)可能在不發(fā)出通知的情況下被清除,因此不能使用sync.Pool存儲(chǔ)需要持久化的對(duì)象。

sync.Pool使用方法

首先看一段示例代碼:

package main

import "sync"

type scanner struct {
	Name string
}

func main() {
	pool := sync.Pool{
		New: func() interface{} {
			return &scanner{
				Name: "json",
			}
		},
	}

	scan := pool.Get().(*scanner)
	println(scan.Name)
	pool.Put(scan)
}

初始化sync.Pool的時(shí)候,需要提供一個(gè)對(duì)象的構(gòu)造函數(shù)New。使用Get從對(duì)象池中獲取對(duì)象,使用Put將對(duì)象放回到對(duì)象池。

可以看出sync.Pool的使用方法非常簡(jiǎn)單,對(duì)外只提供三個(gè)方法:New、Get和Put

  • New方法,使用Get方法從對(duì)象池中獲取對(duì)象的時(shí)候,對(duì)象池中如果沒(méi)有,會(huì)調(diào)用New方法創(chuàng)建一個(gè)新的對(duì)象。
  • Get方法,從對(duì)象池中獲取一個(gè)對(duì)象。
  • Put方法,將對(duì)象放回到對(duì)象池,下次Get的時(shí)候可以復(fù)用。

小結(jié)

本文介紹了sync.Pool的作用和使用方法,下篇文章深入源碼解析sync.Pool。

責(zé)任編輯:姜華 來(lái)源: 今日頭條
相關(guān)推薦

2023-06-28 08:34:02

Bind()函數(shù)JavaScript

2010-10-09 10:30:03

JS event

2023-11-10 08:17:01

分布式搜索引擎

2023-07-03 15:55:05

語(yǔ)法jpa狀態(tài)

2023-06-06 08:28:58

Sync.OnceGolang

2023-06-05 09:23:00

Golang同步工具

2023-06-26 08:28:35

Sync.CondGolang

2025-04-23 08:02:40

2012-05-10 10:53:10

Linuxhistory

2023-07-26 08:58:45

Golang單元測(cè)試

2009-12-28 13:28:03

WPF視頻

2023-04-28 07:56:09

2017-08-18 14:01:44

大數(shù)據(jù)dataWrangle

2025-03-06 08:54:24

泛型類型MapGo1

2012-05-09 10:52:37

Linux監(jiān)控命令

2019-11-07 23:48:12

shell腳本getopts

2009-06-29 17:57:30

ApplicationJSP

2009-12-02 16:04:44

PHP fsockop

2010-01-28 17:07:03

Android Gal

2010-06-01 19:55:30

SVN使用
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)