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

精确控制等待时间
边栏推荐
- Zhongang Mining: the largest application field of new energy or fluorite
- 集合代码练习
- Original translation | comparison of machine learning model service tools: kserve, Seldon core and bentoml
- Codeforces Round #716 (Div. 2)
- 猜拳游戏专题训练
- 关于企业数字化的展望(38/100)
- 空指针异常
- squid代理服務器
- Unity3d button adapts the size according to the text content
- Acwing周赛57-数字操作-(思维+分解质因数)
猜你喜欢

Show the comprehensive strength of strong products, and make the first show of 2022 Lincoln aviator in Southwest China

Icml2022 | scalable depth Gaussian Markov random field

DO280OpenShift访问控制--security policy和章节实验

GoLand permanently activated

Unity3d button adapts the size according to the text content

PCIE知识点-008:PCIE switch的结构

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

大促场景下,如何做好网关高可用防护

Focus! Tips for installing fonts on domestic computers
![Unleash the innovative power of open source database | [Gansu] opengauss meetup has come to a successful conclusion](/img/21/9c5f5122270adea9444ff5f2d199ed.jpg)
Unleash the innovative power of open source database | [Gansu] opengauss meetup has come to a successful conclusion
随机推荐
GFS分布式文件系统
一套系统,减轻人流集中地10倍的通行压力
MySQL Express - day 1 - basic introduction
100 important knowledge points for SQL: in operator
ARCS模型介绍
数组作业题
Let Ma Huateng down! Web3.0, hopeless
创建对象时JVM内存结构
Full record of 2022 open source moment at Huawei partners and Developers Conference
Galaxy Kirin system LAN file sharing tutorial
今晚战码先锋润和赛道第2期直播丨如何参与OpenHarmony代码贡献
华为伙伴暨开发者大会2022开源时刻全纪录
CEPH distributed storage
Love number experiment | Issue 7 - Financial Crisis Analysis Based on random forest
Experience Navicat premium 16, unlimited reset, 14 day trial method (with source code)
Shuttle hides the return button of the AppBar
展现强劲产品综合实力 ,2022 款林肯飞行家Aviator西南首秀
CORBA 架构体系指南(通用对象请求代理体系架构)
Open a new ecological posture | use the wrodpress remote attachment to store it in COS
MYSQL 性能优化 index 函数,隐藏,前缀,hash 索引 使用方法(2)