github.com/anacrolix/torrent@v1.61.0/internal/amortize/amortize.go (about) 1 package amortize 2 3 import ( 4 "math/bits" 5 "sync/atomic" 6 ) 7 8 // A test that progressively returns less and less often, to spread expensive checks out over time 9 // and interesting values. 10 type Atomic struct { 11 herp atomic.Int64 12 derp atomic.Int32 13 } 14 15 func (me *Atomic) Try() bool { 16 m := me.herp.Add(1) 17 shift := me.derp.Load() 18 if m >= 1<<shift { 19 return me.derp.CompareAndSwap(shift, shift+1) 20 } 21 return false 22 } 23 24 var global Atomic 25 26 func Try() bool { 27 return global.Try() 28 } 29 30 type Value struct { 31 count uint 32 } 33 34 func (me *Value) Try() bool { 35 me.count++ 36 return bits.OnesCount(me.count) == 1 37 }