Skip to content

Commit 3011e02

Browse files
authored
Merge pull request #207 from pete-woods/race-condition
pgxstore: Fix race condition in cleanup
2 parents adc38a5 + 5d95719 commit 3011e02

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

pgxstore/pgxstore.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func New(pool *pgxpool.Pool) *PostgresStore {
2828
func NewWithCleanupInterval(pool *pgxpool.Pool, cleanupInterval time.Duration) *PostgresStore {
2929
p := &PostgresStore{pool: pool}
3030
if cleanupInterval > 0 {
31+
p.stopCleanup = make(chan bool)
3132
go p.startCleanup(cleanupInterval)
3233
}
3334
return p
@@ -99,7 +100,6 @@ func (p *PostgresStore) All() (map[string][]byte, error) {
99100
}
100101

101102
func (p *PostgresStore) startCleanup(interval time.Duration) {
102-
p.stopCleanup = make(chan bool)
103103
ticker := time.NewTicker(interval)
104104
for {
105105
select {

pgxstore/pgxstore_test.go

+21
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"context"
66
"os"
77
"reflect"
8+
"strconv"
89
"testing"
910
"time"
1011

@@ -241,6 +242,26 @@ func TestCleanup(t *testing.T) {
241242
}
242243
}
243244

245+
func TestStopCleanup(t *testing.T) {
246+
ctx := context.Background()
247+
248+
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
249+
pool, err := pgxpool.New(ctx, dsn)
250+
if err != nil {
251+
t.Fatal(err)
252+
}
253+
defer pool.Close()
254+
255+
for i := 0; i < 100; i++ {
256+
t.Run(strconv.Itoa(i), func(t *testing.T) {
257+
t.Parallel()
258+
p := New(pool)
259+
time.Sleep(100 * time.Millisecond)
260+
defer p.StopCleanup()
261+
})
262+
}
263+
}
264+
244265
func TestStopNilCleanup(t *testing.T) {
245266
dsn := os.Getenv("SCS_POSTGRES_TEST_DSN")
246267
pool, err := pgxpool.New(context.Background(), dsn)

0 commit comments

Comments
 (0)