首页 > 其他分享 >golang入门(十三)并发锁

golang入门(十三)并发锁

时间:2023-02-22 23:33:14浏览次数:33  
标签:wg 读取数据 read golang 并发 go groutine balance 入门

如果程序用到的数据是多个groutine之间的交互过程中产生的,那么使用上文提到的channel就可以解决了。

如果我们的使用多个groutine访问和修改同一个数据,就需要考虑在并发环境下数据一致性的问题,即线程安全问题。

以存钱为例说明一下问题。假设我们发起一个众筹项目,并发1000个用户的向一个银行银行账号存钱。

package main

import (
"fmt"
"sync"
)

var wg sync.WaitGroup

func Save(income int, balance *int) {

defer wg.Done()
*balance = *balance + income
}

func main() {

balance := 0

//wg.Add(1000)
for s := 0; s < 1000; s++ {
wg.Add(1)
go Save(1, &balance)
}

wg.Wait()

fmt.Println("当前账户余额:", balance)
}

运行结果,正常应该是收到1000元。代码中使用了&符号传递余额变量地址,但是怎么运行结果都不对。这个问题的原因并不是值传递还是引用传递的问题。而是多groutine并发访问变量的时候,变量值因为没有锁定被多个groutine反复修改所致。比如第一个groutine运行的时候获取的变量为0,运算之后变量值被回写为1。但是由于的groutine启动顺序是并不一致,即第200个groutine启动获取变量值的时候,第20个groutine刚好运算结束把结果20写回了变量。那么第200个groutine就拿到变量值20进行了计算了。这就是导致数据丢失的原因。

% go run main.go
当前账户余额: 947
% go run main.go
当前账户余额: 938
% go run main.go
当前账户余额: 948

解决的办法,就是操作变量的时候加个锁。每次只允许一个groutine读写这个变量,读写完成后释放


互斥锁 sync.Mutex 

使用sync.Mutex对象,对数据进行加解锁操作

package main

import (
"fmt"
"sync"
)

var wg sync.WaitGroup

// 声明一个sync.Mutex 类型
var lk sync.Mutex

func Save(income int, balance *int) {

defer wg.Done()
// 操作前给先加锁
lk.Lock()
*balance = *balance + income
// 操作后解锁
lk.Unlock()
}

func main() {

balance := 0

//wg.Add(1000)
for s := 0; s < 1000; s++ {
wg.Add(1)
go Save(1, &balance)
}

wg.Wait()

fmt.Println("当前账户余额:", balance)
}

运行结果,始终与预期一致了

% go run main.go
当前账户余额: 1000
% go run main.go
当前账户余额: 1000
% go run main.go
当前账户余额: 1000


读写锁 sync.RWMutex 

互斥锁虽然解决了数据一致性的问题,但是在运行过程中进程无论是读写要等待解锁,如果是读多写少的场景,那么读groutine就进行了很多无谓等待。读写锁的应对此类需求就非常合适。读写锁的工作原理是当变量要被变更时,无论读写都会block。当数据没有变更时,只读操作允许并发进行。

package main

import (
"fmt"
"sync"
"time"
)

var wg sync.WaitGroup

// 声明一个读写锁sync.RWMutex类型
var lk sync.RWMutex

func Save(thr int, income int, balance *int) {

defer wg.Done()
// 操作前给先加写锁
lk.Lock()

fmt.Printf("write-groutine-< %d >添加写锁\n", thr)
*balance = *balance + income
time.Sleep(time.Millisecond * 1)
fmt.Printf("write-groutine-< %d >解除写锁\n", thr)

// 解除写锁
lk.Unlock()
}

func Show(thr int, balance *int) {
defer wg.Done()
//如果使用互斥锁,即使函数是只读操作,也要等待解锁才可读取

// 读取前加读锁
lk.RLock()

fmt.Printf("read-groutine-< %d >开始读取数据\n", thr)
time.Sleep(time.Millisecond * 1)
fmt.Printf("read-groutine-< %d >完成读取数据\n", thr)

// 解除读锁
lk.RUnlock()
}

func main() {

balance := 0

StartTime := time.Now()

// 写操作3次
for s := 0; s < 3; s++ {
wg.Add(1)
go Save(s, 1, &balance)
}

// 读操作10次
for sh := 0; sh < 10; sh++ {
wg.Add(1)
go Show(sh, &balance)
}

wg.Wait()
fmt.Println("最终账户余额:", balance)

TimeRange := time.Since(StartTime)
fmt.Println("程序运行耗时: ", TimeRange)

}

运行结果,加解锁写操作成对出现。说明在写操作时只有一个groutine在运行,其他groutine被锁住了。读操作的加解锁标记有差距且启动顺序混乱,说明读的时候是多个groutine并发运行没有锁限制。

% go run main.go
write-groutine-< 1 >添加写锁
write-groutine-< 1 >解除写锁
read-groutine-< 1 >开始读取数据 # 1号读groutine开始读数据
read-groutine-< 7 >开始读取数据
read-groutine-< 6 >开始读取数据
read-groutine-< 4 >开始读取数据
read-groutine-< 0 >开始读取数据
read-groutine-< 2 >开始读取数据
read-groutine-< 9 >开始读取数据
read-groutine-< 8 >开始读取数据
read-groutine-< 3 >开始读取数据
read-groutine-< 5 >开始读取数据
read-groutine-< 0 >完成读取数据
read-groutine-< 7 >完成读取数据
read-groutine-< 6 >完成读取数据
read-groutine-< 4 >完成读取数据
read-groutine-< 1 >完成读取数据 # # 1号读groutine完成读数据,耗时1ms
read-groutine-< 5 >完成读取数据
read-groutine-< 9 >完成读取数据
read-groutine-< 8 >完成读取数据
read-groutine-< 3 >完成读取数据
read-groutine-< 2 >完成读取数据
write-groutine-< 0 >添加写锁 # 0号写groutine要等到其他写锁释放,才能添加自己的写锁
write-groutine-< 0 >解除写锁 # 0号写groutine完成写操作耗时1ms,写期间其他groutine挂起
write-groutine-< 2 >添加写锁
write-groutine-< 2 >解除写锁
最终账户余额: 3
程序运行耗时: 45.2403ms

标签:wg,读取数据,read,golang,并发,go,groutine,balance,入门
From: https://blog.51cto.com/830909/6079481

相关文章

  • java之并发编程(上)
    回顾1、线程与进程进程:正在运行的程序,进程包含至少一个或多个线程2、创建线程的方式实现Runable接口继承Thread类(不建议使用,java是单继承,可扩展性差),用start方法通知c......
  • 【TypeScript 4.5】002-第 2 章 TypeScript 入门
    【TypeScript4.5】002-第2章TypeScript入门文章目录​​【TypeScript4.5】002-第2章TypeScript入门​​​​一、发现问题​​​​1、字符串​​​​2、函数​​​......
  • Docker入门学习
    一、安装Docker(Linux)#1、yum包更新到最新yumupdate#2、安装需要的软件包,yum-util提供yum-config-manager功能,另外两个是devicemapper驱动依赖的yuminstall......
  • 使用golang和bluge打造自己的全文搜索引擎
    全文搜索引擎有许多,其中最出名的是elasticsearch,无论是性能还是体验都是最顶尖的,但是对小应用来不友好,因为小应用的硬件资源比较少,所以能够通过库/模块的方式内置在应用中......
  • Vue急速入门-5
    vue-cli创建项目前端工程化,项目>>>(vue-cli),创建处vue项目,单页面应用(spa)vue-cli创建项目开发,在项目中开发,最后上线,一定要编译 '纯粹的html,js,css'vue-cli工具由于......
  • day01-Mybatis介绍与入门
    Mybatis介绍与入门1.官方文档Mybatis中文手册:mybatis–MyBatis3或者MyBatis中文网Maven仓库:MavenRepository:org.mybatis»mybatis»3.5.7(mvnrepository.c......
  • Ansible 快速入门到放弃
    Ansible快速入门到放弃最是人间留不住,朱颜辞镜花辞树。1-Ansible简介Ansible是一个配置管理和配置工具,它使用SSH连接到服务器并运行配置好的任务,服务器上只......
  • golang WEB框架Hertz --- 获取参数
    安装Hertz命令行工具请确保您的Go版本在1.15及以上版本,笔者用的版本是1.18配置好GO的环境后,按照Hertz的命名行工具goinstallgithub.com/cloudwego/hertz/cmd/hz@lates......
  • golang 字符串函数
    1.统计字符串的长度,按字节进行统计packagemainimport"fmt"funcmain(){ vars1string="hello,世界" fmt.Printf("s1字符串的长度为:%v",len(s1))//汉字为......
  • 1 Pytest测试框架入门篇
    1pytest简介pytest是一个非常成熟的python的单元框架,比unittest更灵活,容易上手pytest可以和selenium,requests,appium结合实现web自动化,接口自动化,app自动化pytest......