lock_table_test.go 824 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. }