当前位置:网站首页>Go从入门到实战——共享内存并发机制(笔记)
Go从入门到实战——共享内存并发机制(笔记)
2022-06-27 19:22:00 【积淀 ytu】
共享内存并发机制
Lock

错误示范
package share_test
import (
"testing"
"time"
)
func TestCounter(t *testing.T) {
coun := 0
for i := 0; i < 5000; i++ {
go func() {
coun++
}()
}
time.Sleep(time.Second)
t.Log(coun)
}

在不同的协程中进行自增,增加了相互竞争。不是一个线程安全的程序
正确写法
func TestCounterThreadSafe(t *testing.T) {
var mut sync.Mutex
coun := 0
for i := 0; i < 5000; i++ {
go func() {
defer func() {
mut.Unlock()
}()
mut.Lock()
coun++
}()
}
time.Sleep(time.Second)
t.Log(coun)
}

WaitGroup
func TestCounterWaitGroup(t *testing.T) {
var wg sync.WaitGroup
var mut sync.Mutex
coun := 0
for i := 0; i < 5000; i++ {
wg.Add(1)
go func() {
mut.Lock()
defer func() {
mut.Unlock()
}()
coun++
wg.Done()
}()
}
wg.Wait()
t.Log(coun)
}

精确控制等待时间
边栏推荐
- 使用storcli工具配置RAID,收藏这一篇就够了
- Shell command used in actual work - sed
- Flutter隐藏AppBar的返回按钮
- Codeforces Round #721 (Div. 2)
- 100 important knowledge points that SQL must master: retrieving data
- CORBA 架构体系指南(通用对象请求代理体系架构)
- MySQL performance optimization index function, hidden, prefix, hash index usage (2)
- ABC-Teleporter Setting-(思维+最短路)
- 今晚战码先锋润和赛道第2期直播丨如何参与OpenHarmony代码贡献
- Kirin V10 installation font
猜你喜欢

2021全球独角兽榜发布:中国301家独角兽企业全名单来了!

Animal breeding production virtual simulation teaching system | Sinovel interactive

数据平台调度升级改造 | 从Azkaban 平滑过度到Apache DolphinScheduler 的操作实践

"Good voice" has been singing for 10 years. How can the Chinese language in the starry sky sing well in HKEx?

Focus! Tips for installing fonts on domestic computers

A set of system to reduce 10 times the traffic pressure in crowded areas

01-Golang-环境搭建

银河麒麟系统局域网文件共享教程

关于异常处理的知识整理

Experience Navicat premium 16, unlimited reset, 14 day trial method (with source code)
随机推荐
Share how I take notes
ARCS模型介绍
释放开源数据库创新力量 | 【甘肃】openGauss Meetup圆满结束
Codeforces Global Round 14
Zhongang Mining: the largest application field of new energy or fluorite
CORBA 架构体系指南(通用对象请求代理体系架构)
Contest 2050 and Codeforces Round #718 (Div. 1 + Div. 2)
How to do a good job of gateway high availability protection in the big promotion scenario
TreeSet详解
MYSQL 性能优化 index 函数,隐藏,前缀,hash 索引 使用方法(2)
Share an experience of self positioning + problem solving
MySQL performance optimization index function, hidden, prefix, hash index usage (2)
After being forced to develop the app within 20 days, the group was laid off, and the technical director angrily criticized it: I wish "closure as soon as possible!"
Go从入门到实战——所有任务完成(笔记)
100 important knowledge points that SQL must master: using functions to process data
开启生态新姿势 | 使用 WrodPress 远程附件存储到 COS
爱数课实验 | 第六期-金融反欺诈案例研究
小王的面试训练任务
Shell script controls the startup and shutdown of services - with detailed cases
Love math experiment | phase VI - Financial anti fraud case study