github.com/tursom/GoCollections@v0.3.10/lang/atomic/Int32_test.go (about) 1 /* 2 * Copyright (c) 2022 tursom. All rights reserved. 3 * Use of this source code is governed by a GPL-3 4 * license that can be found in the LICENSE file. 5 */ 6 7 package atomic 8 9 import ( 10 "fmt" 11 "sync" 12 "testing" 13 14 "github.com/tursom/GoCollections/util/time" 15 ) 16 17 func TestInt32_SetBit(t *testing.T) { 18 var i Int32 19 for j := 0; j < 32; j++ { 20 if i.SetBit(j, true) { 21 t.Fail() 22 } 23 if i.Load() != 1<<j { 24 t.Fail() 25 } 26 fmt.Println(i.Load()) 27 if !i.SetBit(j, false) { 28 t.Fail() 29 } 30 if i.Load() != 0 { 31 t.Fail() 32 } 33 } 34 } 35 36 func TestInt32_CompareAndSwapBit(t *testing.T) { 37 var i Int32 38 cond := sync.WaitGroup{} 39 cond.Add(1) 40 for k := 0; k < 128; k++ { 41 id := k 42 go func() { 43 cond.Wait() 44 for j := 0; j < 32; j++ { 45 for !i.CompareAndSwapBit(j, false, true) { 46 } 47 for !i.CompareAndSwapBit(j, true, false) { 48 } 49 } 50 fmt.Printf("%d finished\n", id) 51 }() 52 } 53 cond.Done() 54 time.Sleep(1 * time.Second) 55 fmt.Println(i.Load()) 56 }