mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-22 13:29:01 +00:00
sync: make Pool thread-safe
Make sure the object is locked when trying to modify it. Binary size seems unaffected when not using threading.
This commit is contained in:
committed by
Ron Evans
parent
79164dae71
commit
51504bfd2e
@@ -1,18 +1,24 @@
|
|||||||
package sync
|
package sync
|
||||||
|
|
||||||
|
import "internal/task"
|
||||||
|
|
||||||
// Pool is a very simple implementation of sync.Pool.
|
// Pool is a very simple implementation of sync.Pool.
|
||||||
type Pool struct {
|
type Pool struct {
|
||||||
|
lock task.PMutex
|
||||||
New func() interface{}
|
New func() interface{}
|
||||||
items []interface{}
|
items []interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns an item in the pool, or the value of calling Pool.New() if there are no items.
|
// Get returns an item in the pool, or the value of calling Pool.New() if there are no items.
|
||||||
func (p *Pool) Get() interface{} {
|
func (p *Pool) Get() interface{} {
|
||||||
|
p.lock.Lock()
|
||||||
if len(p.items) > 0 {
|
if len(p.items) > 0 {
|
||||||
x := p.items[len(p.items)-1]
|
x := p.items[len(p.items)-1]
|
||||||
p.items = p.items[:len(p.items)-1]
|
p.items = p.items[:len(p.items)-1]
|
||||||
|
p.lock.Unlock()
|
||||||
return x
|
return x
|
||||||
}
|
}
|
||||||
|
p.lock.Unlock()
|
||||||
if p.New == nil {
|
if p.New == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -21,5 +27,7 @@ func (p *Pool) Get() interface{} {
|
|||||||
|
|
||||||
// Put adds a value back into the pool.
|
// Put adds a value back into the pool.
|
||||||
func (p *Pool) Put(x interface{}) {
|
func (p *Pool) Put(x interface{}) {
|
||||||
|
p.lock.Lock()
|
||||||
p.items = append(p.items, x)
|
p.items = append(p.items, x)
|
||||||
|
p.lock.Unlock()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user