ring struct add lock (#434)

Co-authored-by: liuhuan210 <liuhuan210@jd.com>
This commit is contained in:
理工男
2021-02-03 21:41:10 +08:00
committed by GitHub
parent abab7c2852
commit 7b3c3de35e
2 changed files with 36 additions and 0 deletions

View File

@@ -1,8 +1,11 @@
package collection
import "sync"
type Ring struct {
elements []interface{}
index int
lock sync.Mutex
}
func NewRing(n int) *Ring {
@@ -16,11 +19,16 @@ func NewRing(n int) *Ring {
}
func (r *Ring) Add(v interface{}) {
r.lock.Lock()
defer r.lock.Unlock()
r.elements[r.index%len(r.elements)] = v
r.index++
}
func (r *Ring) Take() []interface{} {
r.lock.Lock()
defer r.lock.Unlock()
var size int
var start int
if r.index > len(r.elements) {