当前位置:网站首页>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)
}

精确控制等待时间
边栏推荐
- SQL必需掌握的100个重要知识点:排序检索数据
- SQL server for circular usage
- Codeforces Round #721 (Div. 2)
- 分享下我是如何做笔记的
- SQL必需掌握的100个重要知识点:组合 WHERE 子句
- Shuttle hides the return button of the AppBar
- White whoring red team goby & POC, how do you call white whoring?
- Navicat premium connection problem --- host 'XXXXXXXX' is not allowed to connect to this MySQL server
- DO280OpenShift访问控制--security policy和章节实验
- Codeforces Round #716 (Div. 2)
猜你喜欢

BTC and eth recapture the lost land! Leading the market recovery? Encryption will enter the "ice age"!

Full record of 2022 open source moment at Huawei partners and Developers Conference

MySQL performance optimization index function, hidden, prefix, hash index usage (2)

100 important knowledge points that SQL must master: sorting and retrieving data

猜拳游戏专题训练

行业案例|从零售之王看银行数字化转型的运营之道

GFS distributed file system

Sharing | intelligent environmental protection - ecological civilization informatization solution (PDF attached)

Wechat applet based service management system for college party members' Home System applet graduation design, Party members, activists, learning, punch in, forum

Modify large online games through CE modifier
随机推荐
BTC and eth recapture the lost land! Leading the market recovery? Encryption will enter the "ice age"!
ABC-Teleporter Setting-(思维+最短路)
麒麟V10安装字体
CORBA 架构体系指南(通用对象请求代理体系架构)
Use the storcli tool to configure raid. Just collect this article
Data platform scheduling upgrade and transformation | operation practice from Azkaban smooth transition to Apache dolphin scheduler
How to participate in openharmony code contribution
MySQL usage notes 1
Golang 使用正则来匹配出子字符串函数
Acwing周赛57-数字操作-(思维+分解质因数)
Educational Codeforces Round 108 (Rated for Div. 2)
爱数课实验 | 第六期-金融反欺诈案例研究
Codeforces Global Round 14
Show the comprehensive strength of strong products, and make the first show of 2022 Lincoln aviator in Southwest China
Unleash the innovative power of open source database | [Gansu] opengauss meetup has come to a successful conclusion
Squid proxy server
如何将队列里面的内容没秒钟执行一次优先级
SQL必需掌握的100个重要知识点:用通配符进行过滤
Animal breeding production virtual simulation teaching system | Sinovel interactive
专题教程——选队长游戏