当前位置:网站首页>Go from introduction to practice -- shared memory concurrency mechanism (notes)
Go from introduction to practice -- shared memory concurrency mechanism (notes)
2022-06-27 21:58:00 【Accumulated Ytu】
Shared memory concurrency mechanism
Lock

Error model
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)
}

Self augmentation in different processes , Increased competition . Not a thread safe program
Write it correctly
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)
}

Precisely control the waiting time
边栏推荐
猜你喜欢

Go从入门到实战——行为的定义和实现(笔记)

Go从入门到实战——channel的关闭和广播(笔记)

The create database of gbase 8A takes a long time to query and is suspected to be stuck

Go从入门到实战——CSP并发机制(笔记)

Go from introduction to actual combat - package (notes)

年薪50W+的测试大鸟都在用这个:Jmeter 脚本开发之——扩展函数

Simulink导出FMU模型文件方法

Go from entry to practice -- CSP concurrency mechanism (note)

Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear

熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊
随机推荐
IO stream code
分享|智慧环保-生态文明信息化解决方案(附PDF)
win11桌面出現“了解此圖片”如何删除
Magic POI error in reading excel template file
[LeetCode]508. 出现次数最多的子树元素和
GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法
[LeetCode]513. Find the value in the lower left corner of the tree
BAT测试专家对web测试和APP测试的总结
[LeetCode]动态规划解分割数组I[Red Fox]
"Apprendre cette image" apparaît sur le Bureau win11 comment supprimer
A method of go accessing gbase 8A database
Summary of gbase 8A database user password security related parameters
Dynamic refresh mapper
Installing Oracle11g under Linux
鲜为人知的mysql导入数据
∫(0→1) ln(1+x) / (x² + 1) dx
Sharing | intelligent environmental protection - ecological civilization informatization solution (PDF attached)
Go从入门到实战——CSP并发机制(笔记)
[LeetCode]515. Find the maximum value in each tree row
GBase 8a OLAP分析函数 cume_dist的使用样例