github.com/moontrade/nogc@v0.1.7/sync/sync_test.go (about) 1 package synchronization 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 ) 8 9 func TestLock(t *testing.T) { 10 //SleepUnsafe(time.Minute) 11 l := NewLock() 12 //l.Lock() 13 l.LockUnsafe() 14 l.UnlockUnsafe() 15 16 wg := &sync.WaitGroup{} 17 wg.Add(2) 18 go func() { 19 defer wg.Done() 20 println("go 1 before") 21 l.LockUnsafe() 22 println("go 1 after. waiting 2 seconds...") 23 SleepUnsafe(time.Second * 2) 24 l.UnlockUnsafe() 25 }() 26 27 go func() { 28 defer wg.Done() 29 println("go 2 before. waiting 2 seconds...") 30 SleepUnsafe(time.Second * 2) 31 //time.Sleep(time.Second*2) 32 l.Unlock() 33 SleepUnsafe(time.Second) 34 l.LockUnsafe() 35 println("go 2 after") 36 l.UnlockUnsafe() 37 }() 38 39 wg.Wait() 40 } 41 42 func BenchmarkRWLock_Lock(b *testing.B) { 43 l := NewLock() 44 b.Run("Unsafe", func(b *testing.B) { 45 for i := 0; i < b.N; i++ { 46 l.LockUnsafe() 47 l.UnlockUnsafe() 48 } 49 }) 50 51 b.Run("Shared Unsafe", func(b *testing.B) { 52 for i := 0; i < b.N; i++ { 53 l.LockSharedUnsafe() 54 l.UnlockSharedUnsafe() 55 } 56 }) 57 b.Run("Shared Safe", func(b *testing.B) { 58 for i := 0; i < b.N; i++ { 59 l.LockShared() 60 l.UnlockShared() 61 } 62 }) 63 mut := &sync.Mutex{} 64 b.Run("Go Mutex", func(b *testing.B) { 65 for i := 0; i < b.N; i++ { 66 mut.Lock() 67 mut.Unlock() 68 } 69 }) 70 71 rw := &sync.RWMutex{} 72 b.Run("Go RWMutex Lock/Unlock", func(b *testing.B) { 73 for i := 0; i < b.N; i++ { 74 rw.Lock() 75 rw.Unlock() 76 } 77 }) 78 79 b.Run("Go RWMutex RLock/RUnlock", func(b *testing.B) { 80 for i := 0; i < b.N; i++ { 81 rw.RLock() 82 rw.RUnlock() 83 } 84 }) 85 }