1 Star 0 Fork 0

c01dface/s-go-example

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
atomic-counters.go 825 Bytes
一键复制 编辑 原始数据 按行查看 历史
c01dface 提交于 2024-12-06 15:02 . add atomic-counters.go
package main
// Here we'll look at using the sync/atomic package for
// atomic counters accessed by multiple goroutines.
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
// We'll use an atomic integer type to represent our counter
var ops atomic.Uint64
// A WaitGroup will help us wait for all goroutines to finish their work.
var wg sync.WaitGroup
// We'll start 50 goroutines that each increment the counter exactly 1000 times
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
for c := 0; c < 1000; c++ {
ops.Add(1)
}
wg.Done()
}()
}
// Wait until all the goroutines are done
wg.Wait()
// Here no goroutines are writing to 'ops', but using Load it's safe
// to atomically read a value even while other goroutines are atomically
// updating it.
fmt.Println("ops:", ops.Load())
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/vmalloc/s-go-example.git
git@gitee.com:vmalloc/s-go-example.git
vmalloc
s-go-example
s-go-example
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385