github.com/gogf/gf/v2@v2.7.4/internal/mutex/mutex_z_unit_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package mutex_test 8 9 import ( 10 "testing" 11 "time" 12 13 "github.com/gogf/gf/v2/container/garray" 14 "github.com/gogf/gf/v2/internal/mutex" 15 "github.com/gogf/gf/v2/test/gtest" 16 ) 17 18 func TestMutexIsSafe(t *testing.T) { 19 gtest.C(t, func(t *gtest.T) { 20 lock := mutex.New() 21 t.Assert(lock.IsSafe(), false) 22 23 lock = mutex.New(false) 24 t.Assert(lock.IsSafe(), false) 25 26 lock = mutex.New(false, false) 27 t.Assert(lock.IsSafe(), false) 28 29 lock = mutex.New(true, false) 30 t.Assert(lock.IsSafe(), true) 31 32 lock = mutex.New(true, true) 33 t.Assert(lock.IsSafe(), true) 34 35 lock = mutex.New(true) 36 t.Assert(lock.IsSafe(), true) 37 }) 38 } 39 40 func TestSafeMutex(t *testing.T) { 41 gtest.C(t, func(t *gtest.T) { 42 safeLock := mutex.New(true) 43 array := garray.New(true) 44 45 go func() { 46 safeLock.Lock() 47 array.Append(1) 48 time.Sleep(1000 * time.Millisecond) 49 array.Append(1) 50 safeLock.Unlock() 51 }() 52 go func() { 53 time.Sleep(100 * time.Millisecond) 54 safeLock.Lock() 55 array.Append(1) 56 time.Sleep(2000 * time.Millisecond) 57 array.Append(1) 58 safeLock.Unlock() 59 }() 60 time.Sleep(500 * time.Millisecond) 61 t.Assert(array.Len(), 1) 62 time.Sleep(800 * time.Millisecond) 63 t.Assert(array.Len(), 3) 64 time.Sleep(1000 * time.Millisecond) 65 t.Assert(array.Len(), 3) 66 time.Sleep(1000 * time.Millisecond) 67 t.Assert(array.Len(), 4) 68 }) 69 } 70 71 func TestUnsafeMutex(t *testing.T) { 72 gtest.C(t, func(t *gtest.T) { 73 var ( 74 unsafeLock = mutex.New() 75 array = garray.New(true) 76 ) 77 78 go func() { 79 unsafeLock.Lock() 80 array.Append(1) 81 time.Sleep(1000 * time.Millisecond) 82 array.Append(1) 83 unsafeLock.Unlock() 84 }() 85 go func() { 86 time.Sleep(100 * time.Millisecond) 87 unsafeLock.Lock() 88 array.Append(1) 89 time.Sleep(2000 * time.Millisecond) 90 array.Append(1) 91 unsafeLock.Unlock() 92 }() 93 time.Sleep(500 * time.Millisecond) 94 t.Assert(array.Len(), 2) 95 time.Sleep(1000 * time.Millisecond) 96 t.Assert(array.Len(), 3) 97 time.Sleep(500 * time.Millisecond) 98 t.Assert(array.Len(), 3) 99 time.Sleep(1000 * time.Millisecond) 100 t.Assert(array.Len(), 4) 101 }) 102 }