Go语言atomic原子操作
所属分类 go
浏览量 815
go doc sync/atomic
import "sync/atomic"
func AddInt32(addr *int32, delta int32) (new int32)
func AddInt64(addr *int64, delta int64) (new int64)
func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
func LoadInt32(addr *int32) (val int32)
func LoadInt64(addr *int64) (val int64)
func StoreInt32(addr *int32, val int32)
func StoreInt64(addr *int64, val int64)
Add CompareAndSwap Load Store
读写 增加 比较和交换
var count int32
atomic.AddInt32(&count,1)
并发递增计数
count3.go
package main
import "fmt"
import "time"
import "sync"
import "sync/atomic"
var count int32
var NUM = 1000000
var GONUM = 100
var wg sync.WaitGroup
func main() {
wg.Add(GONUM)
start := time.Now()
for i := 0; i < GONUM; i++ {
go countadd()
}
wg.Wait()
cost := time.Since(start)
fmt.Println(count,cost)
}
func countadd(){
defer wg.Done()
for i := 0; i < NUM; i++ {
atomic.AddInt32(&count,1)
}
}
go run count3.go
100000000 3.296716571s
go run count3.go
100000000 3.185218237s
完整代码
https://gitee.com/dyyx/hellocode/blob/master/web/tech/go/demo/count3.go
上一篇
下一篇
学习GO要了解的几个特性
GO 并发递增计数实例
Go并发构建模块
GO mutex 与 atomic 性能对比
cannot find GOROOT directory
自定义springboot starter