You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
824 B

1 year ago
1 year ago
1 year ago
  1. package util
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sync"
  6. "testing"
  7. "time"
  8. )
  9. func TestOrderedLock(t *testing.T) {
  10. lt := NewLockTable[string]()
  11. var wg sync.WaitGroup
  12. // Simulate transactions requesting locks
  13. for i := 1; i <= 50; i++ {
  14. wg.Add(1)
  15. go func(i int) {
  16. defer wg.Done()
  17. key := "resource"
  18. lockType := SharedLock
  19. if i%5 == 0 {
  20. lockType = ExclusiveLock
  21. }
  22. // Simulate attempting to acquire the lock
  23. lock := lt.AcquireLock("", key, lockType)
  24. // Lock acquired, perform some work
  25. fmt.Printf("ActiveLock %d acquired lock %v\n", lock.ID, lockType)
  26. // Simulate some work
  27. time.Sleep(time.Duration(rand.Int31n(10)*10) * time.Millisecond)
  28. // Release the lock
  29. lt.ReleaseLock(key, lock)
  30. fmt.Printf("ActiveLock %d released lock %v\n", lock.ID, lockType)
  31. }(i)
  32. }
  33. wg.Wait()
  34. }