spinlock_test.go 677 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package syncx
  2. import (
  3. "sync"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestTryLock(t *testing.T) {
  9. var lock SpinLock
  10. assert.True(t, lock.TryLock())
  11. assert.False(t, lock.TryLock())
  12. lock.Unlock()
  13. assert.True(t, lock.TryLock())
  14. }
  15. func TestSpinLock(t *testing.T) {
  16. var lock SpinLock
  17. lock.Lock()
  18. assert.False(t, lock.TryLock())
  19. lock.Unlock()
  20. assert.True(t, lock.TryLock())
  21. }
  22. func TestSpinLockRace(t *testing.T) {
  23. var lock SpinLock
  24. lock.Lock()
  25. var wait sync.WaitGroup
  26. wait.Add(1)
  27. go func() {
  28. lock.Lock()
  29. lock.Unlock()
  30. wait.Done()
  31. }()
  32. time.Sleep(time.Millisecond * 100)
  33. lock.Unlock()
  34. wait.Wait()
  35. assert.True(t, lock.TryLock())
  36. }