github.com/gogf/gf@v1.16.9/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/container/garray" 14 "github.com/gogf/gf/internal/mutex" 15 "github.com/gogf/gf/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(100 * time.Millisecond) 49 array.Append(1) 50 safeLock.Unlock() 51 }() 52 go func() { 53 time.Sleep(10 * time.Millisecond) 54 safeLock.Lock() 55 array.Append(1) 56 time.Sleep(200 * time.Millisecond) 57 array.Append(1) 58 safeLock.Unlock() 59 }() 60 time.Sleep(50 * time.Millisecond) 61 t.Assert(array.Len(), 1) 62 time.Sleep(80 * time.Millisecond) 63 t.Assert(array.Len(), 3) 64 time.Sleep(100 * time.Millisecond) 65 t.Assert(array.Len(), 3) 66 time.Sleep(100 * 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 unsafeLock := mutex.New() 74 array := garray.New(true) 75 76 go func() { 77 unsafeLock.Lock() 78 array.Append(1) 79 time.Sleep(100 * time.Millisecond) 80 array.Append(1) 81 unsafeLock.Unlock() 82 }() 83 go func() { 84 time.Sleep(10 * time.Millisecond) 85 unsafeLock.Lock() 86 array.Append(1) 87 time.Sleep(200 * time.Millisecond) 88 array.Append(1) 89 unsafeLock.Unlock() 90 }() 91 time.Sleep(50 * time.Millisecond) 92 t.Assert(array.Len(), 2) 93 time.Sleep(100 * time.Millisecond) 94 t.Assert(array.Len(), 3) 95 time.Sleep(50 * time.Millisecond) 96 t.Assert(array.Len(), 3) 97 time.Sleep(100 * time.Millisecond) 98 t.Assert(array.Len(), 4) 99 }) 100 }