1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
package refclose
import (
"sync"
"testing"
"github.com/bradfitz/iter"
"github.com/stretchr/testify/assert"
)
type refTest struct {
pool RefPool
key interface{}
objs map[*object]struct{}
t *testing.T
}
func (me *refTest) run() {
me.objs = make(map[*object]struct{})
var (
mu sync.Mutex
curObj *object
wg sync.WaitGroup
)
for range iter.N(1000) {
wg.Add(1)
go func() {
defer wg.Done()
ref := me.pool.NewRef(me.key)
mu.Lock()
if curObj == nil {
curObj = new(object)
me.objs[curObj] = struct{}{}
}
// obj := curObj
mu.Unlock()
ref.SetCloser(func() {
mu.Lock()
if curObj.closed {
panic("object already closed")
}
curObj.closed = true
curObj = nil
mu.Unlock()
})
ref.Release()
}()
}
wg.Wait()
me.t.Logf("created %d objects", len(me.objs))
assert.True(me.t, len(me.objs) >= 1)
for obj := range me.objs {
assert.True(me.t, obj.closed)
}
}
type object struct {
closed bool
}
func Test(t *testing.T) {
(&refTest{
key: 3,
t: t,
}).run()
}
|