github.com/goki/ki@v1.1.11/fatomic/fatomic.go (about) 1 // Copyright (c) 2019, The Emergent Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package fatomic provides floating-point atomic operations 6 package fatomic 7 8 import ( 9 "math" 10 "sync/atomic" 11 "unsafe" 12 ) 13 14 // from: 15 // https://stackoverflow.com/questions/27492349/go-atomic-addfloat32 16 17 // AddFloat32 adds given increment to a float32 value atomically 18 func AddFloat32(val *float32, inc float32) (nval float32) { 19 for { 20 old := *val 21 nval = old + inc 22 if atomic.CompareAndSwapUint32( 23 (*uint32)(unsafe.Pointer(val)), 24 math.Float32bits(old), 25 math.Float32bits(nval), 26 ) { 27 break 28 } 29 } 30 return 31 } 32 33 // AddFloat64 adds given increment to a float64 value atomically 34 func AddFloat64(val *float64, inc float64) (nval float64) { 35 for { 36 old := *val 37 nval = old + inc 38 if atomic.CompareAndSwapUint64( 39 (*uint64)(unsafe.Pointer(val)), 40 math.Float64bits(old), 41 math.Float64bits(nval), 42 ) { 43 break 44 } 45 } 46 return 47 }