2023-08-11 08:32:43 +00:00
|
|
|
package sync
|
2023-04-21 10:49:05 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"golang.org/x/sync/errgroup"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestKeyLocker(t *testing.T) {
|
|
|
|
taken := false
|
|
|
|
eg, _ := errgroup.WithContext(context.Background())
|
2023-08-11 08:32:43 +00:00
|
|
|
keyLocker := NewKeyLocker[int]()
|
2023-04-21 10:49:05 +00:00
|
|
|
for i := 0; i < 100; i++ {
|
|
|
|
eg.Go(func() error {
|
2023-08-11 08:32:43 +00:00
|
|
|
keyLocker.Lock(0)
|
|
|
|
defer keyLocker.Unlock(0)
|
2023-04-21 10:49:05 +00:00
|
|
|
|
|
|
|
require.False(t, taken)
|
|
|
|
taken = true
|
|
|
|
require.True(t, taken)
|
|
|
|
time.Sleep(10 * time.Millisecond)
|
|
|
|
taken = false
|
|
|
|
require.False(t, taken)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
require.NoError(t, eg.Wait())
|
|
|
|
}
|