Created
January 6, 2017 18:48
-
-
Save FZambia/61bd96b198858d0797718b24e638be74 to your computer and use it in GitHub Desktop.
Timer pool for Go language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pools | |
import ( | |
"sync" | |
"time" | |
) | |
var timerPool sync.Pool | |
// AcquireTimer returns time from pool if possible. | |
func AcquireTimer(d time.Duration) *time.Timer { | |
v := timerPool.Get() | |
if v == nil { | |
return time.NewTimer(d) | |
} | |
tm := v.(*time.Timer) | |
if tm.Reset(d) { | |
// active timer? | |
return time.NewTimer(d) | |
} | |
return tm | |
} | |
// ReleaseTimer returns timer into pool. | |
func ReleaseTimer(tm *time.Timer) { | |
if !tm.Stop() { | |
// tm.Stop() returns false if the timer has already expired or been stopped. | |
// We can't be sure that timer.C will not be filled after timer.Stop(), | |
// see https://groups.google.com/forum/#!topic/golang-nuts/-8O3AknKpwk | |
// | |
// The tip from manual to read from timer.C possibly blocks caller if caller | |
// has already done <-timer.C. Non-blocking read from timer.C with select does | |
// not help either because send is done concurrently from another goroutine. | |
return | |
} | |
timerPool.Put(tm) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment