Skip to content

Instantly share code, notes, and snippets.

@axgle
Last active December 18, 2022 09:56
Show Gist options
  • Save axgle/11238189 to your computer and use it in GitHub Desktop.
Save axgle/11238189 to your computer and use it in GitHub Desktop.

What is sync.Pool in golang and How to use it

sync.Pool (1/2)

Many Go libraries include custom thread-safe free lists, like this:

var objPool = make(chan *Object, 10)

func obj() *Object {
	select {
	case p := <-objPool:
		return p
	default:
	}
	return NewObject()
}

func objPut(p *Object) {
	select {
	case objPool <- p:
	default:
	}
}

p := obj()
// use p
objPut(p)
  • sync.Pool (2/2)

The sync.Pool type provides a general thread-safe global free list.

It allows the runtime to reclaim entries when appropriate (for example, during garbage collection).

var objPool = sync.Pool{
	New: func() interface{} {
		return NewObject()
	},
}

p := objPool.Get().(*Object)
// use p
objPool.Put(p)

From: https://code.google.com/p/go/source/browse/2014/go1.3.slide?spec=svn.talks.5c1ef7ac81bc9625b770bc3331c3252de6ef7946&repo=talks&r=5c1ef7ac81bc9625b770bc3331c3252de6ef7946

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment