github.com/zhongdalu/gf@v1.0.0/g/internal/mutex/mutex_z_unit_test.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/gf. 6 7 package mutex_test 8 9 import ( 10 "github.com/zhongdalu/gf/g/container/garray" 11 "github.com/zhongdalu/gf/g/internal/mutex" 12 "github.com/zhongdalu/gf/g/test/gtest" 13 "testing" 14 "time" 15 ) 16 17 func TestMutexIsSafe(t *testing.T) { 18 gtest.Case(t, func() { 19 lock := mutex.New() 20 gtest.Assert(lock.IsSafe(), true) 21 22 lock = mutex.New(false) 23 gtest.Assert(lock.IsSafe(), true) 24 25 lock = mutex.New(false, false) 26 gtest.Assert(lock.IsSafe(), true) 27 28 lock = mutex.New(true, false) 29 gtest.Assert(lock.IsSafe(), false) 30 31 lock = mutex.New(true, true) 32 gtest.Assert(lock.IsSafe(), false) 33 34 lock = mutex.New(true) 35 gtest.Assert(lock.IsSafe(), false) 36 }) 37 } 38 39 func TestSafeMutex(t *testing.T) { 40 gtest.Case(t, func() { 41 safeLock := mutex.New(false) 42 array := garray.New() 43 44 go func() { 45 safeLock.Lock() 46 array.Append(1) 47 time.Sleep(100 * time.Millisecond) 48 array.Append(1) 49 safeLock.Unlock() 50 }() 51 go func() { 52 time.Sleep(10 * time.Millisecond) 53 safeLock.Lock() 54 array.Append(1) 55 time.Sleep(200 * time.Millisecond) 56 array.Append(1) 57 safeLock.Unlock() 58 }() 59 time.Sleep(50 * time.Millisecond) 60 gtest.Assert(array.Len(), 1) 61 time.Sleep(80 * time.Millisecond) 62 gtest.Assert(array.Len(), 3) 63 time.Sleep(100 * time.Millisecond) 64 gtest.Assert(array.Len(), 3) 65 time.Sleep(100 * time.Millisecond) 66 gtest.Assert(array.Len(), 4) 67 }) 68 } 69 70 func TestUnsafeMutex(t *testing.T) { 71 gtest.Case(t, func() { 72 unsafeLock := mutex.New(true) 73 array := garray.New() 74 75 go func() { 76 unsafeLock.Lock() 77 array.Append(1) 78 time.Sleep(100 * time.Millisecond) 79 array.Append(1) 80 unsafeLock.Unlock() 81 }() 82 go func() { 83 time.Sleep(10 * time.Millisecond) 84 unsafeLock.Lock() 85 array.Append(1) 86 time.Sleep(200 * time.Millisecond) 87 array.Append(1) 88 unsafeLock.Unlock() 89 }() 90 time.Sleep(50 * time.Millisecond) 91 gtest.Assert(array.Len(), 2) 92 time.Sleep(100 * time.Millisecond) 93 gtest.Assert(array.Len(), 3) 94 time.Sleep(50 * time.Millisecond) 95 gtest.Assert(array.Len(), 3) 96 time.Sleep(100 * time.Millisecond) 97 gtest.Assert(array.Len(), 4) 98 }) 99 }