Skip to content

Commit

Permalink
sync: make Pool thread-safe
Browse files Browse the repository at this point in the history
Make sure the object is locked when trying to modify it.
Binary size seems unaffected when not using threading.
  • Loading branch information
aykevl authored and deadprogram committed Nov 22, 2024
1 parent 79164da commit 51504bf
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/sync/pool.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
package sync

import "internal/task"

// Pool is a very simple implementation of sync.Pool.
type Pool struct {
lock task.PMutex
New func() interface{}
items []interface{}
}

// Get returns an item in the pool, or the value of calling Pool.New() if there are no items.
func (p *Pool) Get() interface{} {
p.lock.Lock()
if len(p.items) > 0 {
x := p.items[len(p.items)-1]
p.items = p.items[:len(p.items)-1]
p.lock.Unlock()
return x
}
p.lock.Unlock()
if p.New == nil {
return nil
}
Expand All @@ -21,5 +27,7 @@ func (p *Pool) Get() interface{} {

// Put adds a value back into the pool.
func (p *Pool) Put(x interface{}) {
p.lock.Lock()
p.items = append(p.items, x)
p.lock.Unlock()
}

0 comments on commit 51504bf

Please sign in to comment.