From 2f17b3e2599a1ae8b0cc448c623fa0c25d6c50cb Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Fri, 11 Nov 2022 18:55:27 -0600 Subject: [PATCH] Fix create resource concurrently with Stat call race https://github.com/jackc/pgx/issues/1148#issuecomment-1304898720 --- pool.go | 4 ++++ pool_test.go | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/pool.go b/pool.go index e18658c..f9190d6 100644 --- a/pool.go +++ b/pool.go @@ -427,8 +427,12 @@ func (p *Pool[T]) initResourceValue(ctx context.Context, res *Resource[T]) (*Res return } + // The resource is already in p.allResources where it might be read. So we need to acquire the lock to update its + // status. + p.mux.Lock() res.value = value res.status = resourceStatusAcquired + p.mux.Unlock() // This select works because the channel is unbuffered. select { diff --git a/pool_test.go b/pool_test.go index 45ee822..ac0d15b 100644 --- a/pool_test.go +++ b/pool_test.go @@ -985,6 +985,11 @@ func TestStress(t *testing.T) { res.Release() } }, + // Stat + func() { + stat := pool.Stat() + assert.NotNil(t, stat) + }, } workerCount := int(poolSize) * 2