当前位置:网站首页>golang并发编程之Mutex互斥锁实现同步和原子操作(atomic)
golang并发编程之Mutex互斥锁实现同步和原子操作(atomic)
2022-06-22 03:08:00 【ManNiaoQinFen】
使用Mutex互斥锁,加锁可以保证资源不被其他协程修改
package main
import (
"fmt"
"sync"
)
var m int = 100
var lock sync.Mutex
var wt sync.WaitGroup
func add() {
defer wt.Done()
lock.Lock() //加锁后可实现资源如m,不被其他协程操作
m += 1
fmt.Printf("m++: %v\n", m)
lock.Unlock()
}
func sub() {
defer wt.Done()
lock.Lock()
m -= 1
fmt.Printf("m--: %v\n", m)
lock.Unlock()
}
func main() {
for i := 0; i < 100; i++ {
wt.Add(1)
go add()
wt.Add(1)
go sub()
}
wt.Wait() //保证其他协程先完成
fmt.Printf("m: %v\n", m)
}
加Mutex之前,m的值不一定等于100,加锁后值等于100
atomic操作
package main
import (
"fmt"
"sync/atomic"
"time"
)
var i int32 = 100
func add() {
atomic.AddInt32(&i, 1)
}
func sub() {
atomic.AddInt32(&i, -1)
}
func main() {
for i := 0; i < 100; i++ {
go add()
go sub()
}
time.Sleep(time.Second * 3)
fmt.Printf("i: %v\n", i)
}
运行结果
i: 100
边栏推荐
- [microservices | Nacos] quickly realize the configuration center function of Nacos, and complete configuration update and version iteration
- EFCore中的主键
- Redis6.0新特性(下)
- [pwn basics]pwntools learning
- 【NVMe2.0b 10】Controller Shutdown 与 NVM Subsystem Shutdown
- C1-qt idea of realizing simple calculator 2021.10.15
- Tag dynamic programming - preliminary knowledge for question brushing -1 Dynamic programming five part problem solving method + lt.509 Fibonacci number / Sword finger offer 10 I + lt.70. Climbing stai
- Force buckle 160 Intersecting linked list
- [nvme2.0b 5] sous - système nvm
- Use the serialize common command
猜你喜欢

FastDFS-6.0.6

Implementation principle and application practice of Flink CDC mongodb connector

A solution to memory leak in server

【NVMe2.0b 6】NVMe 队列模型

Irregular layout of table label

克隆的vmware虚拟主机网卡无法启动解决办法

【NVMe2.0b 5】NVM Subsystem

Force buckle 160 Intersecting linked list

Redis6.0新特性(下)

uv_ loop_ Init() process
随机推荐
HarmonyOS鸿蒙使用ORM Bee访问数据库实例
MySQL field type and corresponding length & bytes
Sword finger offer 57 Next node of binary tree
Sword finger offer 56 Delete duplicate nodes of the linked list
Irregular layout of table label
TX2 attaching SD card, jtop
NXP imx8mp学习记录
Sword finger offer 28 Symmetric binary tree
[kubernetes series] what is kubernetes?
tag动态规划-刷题预备知识-1.动态规划五部曲解题法 + lt.509. 斐波那契数/ 剑指Offer 10.I + lt.70. 爬楼梯彻底解惑 + 面试真题扩展
Force buckle 141 Circular linked list
高考后网上查询信息,注意防范没有 SSL证书的网站
Day17QtQLcdNumber2021-10-22
【Kubernetes 系列】Kubernetes 是什么?
360edr planing
Overview of web framework and program development
Figure base de données ongdb version V - 1.0.2
[microservices | Nacos] quickly realize the configuration center function of Nacos, and complete configuration update and version iteration
uv_ loop_ Init() process
【NVMe2.0b 12】NVM 容量模型