Skip to content

Commit c6300df

Browse files
committed
test: wait close avoid data race
1 parent a02f809 commit c6300df

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-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: 8 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
@@ -66,8 +69,10 @@ func (l *redisLocker) TryLock(ctx context.Context, key string) (bool, context.Co
6669
// It will stop extending the locks and refuse to acquire new locks.
6770
// In actual use, it is not necessary to call this function.
6871
// But it's useful in tests to release resources.
72+
// It could take some time since it waits for the extending goroutine to finish.
6973
func (l *redisLocker) Close() error {
7074
l.closed.Store(true)
75+
l.extendWg.Wait()
7176
return nil
7277
}
7378

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

120125
func (l *redisLocker) startExtend() {
121126
if l.closed.Load() {
127+
l.extendWg.Done()
122128
return
123129
}
124130

0 commit comments

Comments
 (0)