Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Forked from axgle/sync.Pool.md
Created August 24, 2016 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanmhlv/23054671883fc33e7a469601179bdb81 to your computer and use it in GitHub Desktop.
Save yanmhlv/23054671883fc33e7a469601179bdb81 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