github.com/kubewharf/katalyst-core@v0.5.3/pkg/util/syntax/lock_test.go (about) 1 /* 2 Copyright 2022 The Katalyst Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 /* 18 native locking functions in package-sync doesn't contain deadlock-detecting logic, 19 to avoid deadlock during runtime processes, it's advised to use locking functions 20 here to provide deadlock-detecting when it exceeds timeout 21 */ 22 23 package syntax 24 25 import ( 26 "testing" 27 "time" 28 29 "github.com/stretchr/testify/assert" 30 31 "github.com/kubewharf/katalyst-core/pkg/metrics" 32 ) 33 34 func TestLock(t *testing.T) { 35 t.Parallel() 36 37 m := NewMutexWithPeriod(metrics.DummyMetrics{}, time.Second) 38 assert.Equal(t, m.Lock(), 0) 39 go func() { 40 assert.Greater(t, m.Lock(), 0) 41 m.Unlock() 42 }() 43 time.Sleep(time.Second * 2) 44 m.Unlock() 45 time.Sleep(time.Second) 46 } 47 48 func TestLockMultipleTimes(t *testing.T) { 49 t.Parallel() 50 51 m := NewMutexWithPeriod(metrics.DummyMetrics{}, time.Second) 52 assert.Equal(t, m.Lock(), 0) 53 go func() { 54 assert.Greater(t, m.Lock(), 1) 55 m.Unlock() 56 }() 57 time.Sleep(time.Second * 4) 58 m.Unlock() 59 time.Sleep(time.Second) 60 } 61 62 func TestRWLock(t *testing.T) { 63 t.Parallel() 64 65 rm := NewRWMutexWithPeriod(metrics.DummyMetrics{}, time.Second) 66 assert.Equal(t, rm.Lock(), 0) 67 go func() { 68 assert.Greater(t, rm.Lock(), 0) 69 rm.Unlock() 70 }() 71 time.Sleep(time.Second * 2) 72 rm.Unlock() 73 time.Sleep(time.Second) 74 } 75 76 func TestRWRLock(t *testing.T) { 77 t.Parallel() 78 79 rm := NewRWMutexWithPeriod(metrics.DummyMetrics{}, time.Second) 80 assert.Equal(t, rm.Lock(), 0) 81 go func() { 82 assert.Greater(t, rm.RLock(), 0) 83 rm.RUnlock() 84 }() 85 time.Sleep(time.Second * 2) 86 rm.Unlock() 87 time.Sleep(time.Second) 88 }