github.com/teng231/glock@v1.1.11/optimistic_lock_test.go (about) 1 package glock 2 3 import ( 4 "fmt" 5 "log" 6 "sync" 7 "testing" 8 "time" 9 ) 10 11 /* 12 Run test: go test -run TestOptimisticRun 13 go test -bench BenchmarkOptimistic100t -benchmem 14 go test -bench BenchmarkOptimistic10000t -benchmem 15 ?*/ 16 func TestOptimisticRun(t *testing.T) { 17 ol, err := CreateOptimisticLock("localhost:6379", "", "test_", time.Second) 18 if err != nil { 19 panic(err) 20 } 21 if err := ol.Lock("key1"); err != nil { 22 log.Print(err) 23 } 24 if err := ol.Lock("key1"); err != nil { 25 log.Print(err) 26 } 27 if err := ol.Lock("key1"); err != nil { 28 log.Print(err) 29 } 30 if err := ol.Unlock("key1"); err != nil { 31 log.Print(err) 32 } 33 if err := ol.Lock("key1"); err != nil { 34 log.Print(err) 35 } 36 } 37 func BenchmarkOptimistic100t(t *testing.B) { 38 ol, err := CreateOptimisticLock("localhost:6379", "", "test_", time.Second) 39 if err != nil { 40 panic(err) 41 } 42 for i := 0; i < 100; i++ { 43 if err := ol.Lock(fmt.Sprintf("key_%v", i)); err != nil { 44 log.Print(err) 45 } 46 if err := ol.Unlock(fmt.Sprintf("key_%v", i)); err != nil { 47 log.Print(err) 48 } 49 } 50 } 51 func BenchmarkOptimistic10000Miltiples(t *testing.B) { 52 ol, err := CreateOptimisticLock("localhost:6379", "", "test_", time.Second) 53 if err != nil { 54 panic(err) 55 } 56 c := make(chan string, 1000) 57 wg := &sync.WaitGroup{} 58 for i := 0; i < 50; i++ { 59 go func() { 60 for { 61 item := <-c 62 if err := ol.Lock(item); err != nil { 63 log.Print(err) 64 } 65 if err := ol.Unlock(item); err != nil { 66 log.Print(err) 67 } 68 wg.Done() 69 } 70 71 }() 72 } 73 for i := 0; i < 10000; i++ { 74 c <- fmt.Sprintf("key_%v", i) 75 wg.Add(1) 76 } 77 wg.Wait() 78 } 79 80 func BenchmarkOptimistic10000t(t *testing.B) { 81 ol, err := CreateOptimisticLock("localhost:6379", "", "test_", time.Second) 82 if err != nil { 83 panic(err) 84 } 85 for i := 0; i < 10000; i++ { 86 if err := ol.Lock(fmt.Sprintf("key_%v", i)); err != nil { 87 log.Print(err) 88 } 89 if err := ol.Unlock(fmt.Sprintf("key_%v", i)); err != nil { 90 log.Print(err) 91 } 92 } 93 }