Skip to content

Commit f372969

Browse files
committed
test: avoid data race
1 parent a02f809 commit f372969

File tree

2 files changed

+7
-7
lines changed

2 files changed

+7
-7
lines changed

modules/globallock/locker_test.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,6 @@ func TestLocker(t *testing.T) {
2929
oldExpiry := redisLockExpiry
3030
redisLockExpiry = 5 * time.Second // make it shorter for testing
3131
defer func() {
32-
// Avoid data race.
33-
// The startExtend goroutine may still be running and reading redisLockExpiry.
34-
// Wait for a while since it will be stopped soon after Close is called.
35-
time.Sleep(time.Second)
36-
3732
redisLockExpiry = oldExpiry
3833
}()
3934

modules/globallock/redis_locker.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,9 @@ var redisLockExpiry = 30 * time.Second
2626
type redisLocker struct {
2727
rs *redsync.Redsync
2828

29-
mutexM sync.Map
30-
closed atomic.Bool
29+
mutexM sync.Map
30+
closed atomic.Bool
31+
extendWg sync.WaitGroup
3132
}
3233

3334
var _ Locker = &redisLocker{}
@@ -40,6 +41,8 @@ func NewRedisLocker(connection string) Locker {
4041
),
4142
),
4243
}
44+
45+
l.extendWg.Add(1)
4346
l.startExtend()
4447

4548
return l
@@ -68,6 +71,7 @@ func (l *redisLocker) TryLock(ctx context.Context, key string) (bool, context.Co
6871
// But it's useful in tests to release resources.
6972
func (l *redisLocker) Close() error {
7073
l.closed.Store(true)
74+
l.extendWg.Wait()
7175
return nil
7276
}
7377

@@ -119,6 +123,7 @@ func (l *redisLocker) lock(ctx context.Context, key string, tries int) (context.
119123

120124
func (l *redisLocker) startExtend() {
121125
if l.closed.Load() {
126+
l.extendWg.Done()
122127
return
123128
}
124129

0 commit comments

Comments
 (0)