gitee.com/go-spring2/spring-base@v1.1.3/atomic/int64_test.go (about) 1 /* 2 * Copyright 2012-2019 the original author or 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 * https://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 package atomic_test 18 19 import ( 20 "reflect" 21 "sync" 22 "testing" 23 "unsafe" 24 25 "gitee.com/go-spring2/spring-base/assert" 26 "gitee.com/go-spring2/spring-base/atomic" 27 "gitee.com/go-spring2/spring-base/json" 28 ) 29 30 func TestInt64(t *testing.T) { 31 32 // atomic.Int64 and int64 occupy the same space 33 assert.Equal(t, unsafe.Sizeof(atomic.Int64{}), uintptr(8)) 34 35 var i atomic.Int64 36 assert.Equal(t, i.Load(), int64(0)) 37 38 v := i.Add(5) 39 assert.Equal(t, v, int64(5)) 40 assert.Equal(t, i.Load(), int64(5)) 41 42 i.Store(1) 43 assert.Equal(t, i.Load(), int64(1)) 44 45 old := i.Swap(2) 46 assert.Equal(t, old, int64(1)) 47 assert.Equal(t, i.Load(), int64(2)) 48 49 swapped := i.CompareAndSwap(2, 3) 50 assert.True(t, swapped) 51 assert.Equal(t, i.Load(), int64(3)) 52 53 swapped = i.CompareAndSwap(2, 3) 54 assert.False(t, swapped) 55 assert.Equal(t, i.Load(), int64(3)) 56 57 bytes, _ := json.Marshal(&i) 58 assert.Equal(t, string(bytes), "3") 59 } 60 61 func TestReflectInt64(t *testing.T) { 62 63 var s struct { 64 I atomic.Int64 65 } 66 67 var wg sync.WaitGroup 68 wg.Add(2) 69 go func() { 70 defer wg.Done() 71 addr := reflect.ValueOf(&s).Elem().Field(0).Addr() 72 v, ok := addr.Interface().(*atomic.Int64) 73 assert.True(t, ok) 74 for i := 0; i < 10; i++ { 75 v.Add(1) 76 } 77 }() 78 go func() { 79 defer wg.Done() 80 addr := reflect.ValueOf(&s).Elem().Field(0).Addr() 81 v, ok := addr.Interface().(*atomic.Int64) 82 assert.True(t, ok) 83 for i := 0; i < 10; i++ { 84 v.Add(2) 85 } 86 }() 87 wg.Wait() 88 assert.Equal(t, int64(30), s.I.Load()) 89 }