go同步锁 sync mutex

goroutine

http://127.0.0.1:3999/concurrency/11

go tour 到此 就结束了.

继续 学习 可以 从 以下网站

文档

https://golang.org/doc/

https://golang.org/doc/code

https://golang.org/doc/codewalk/functions/

博客

https://go.dev/blog/

wiki 服务器教程

服务器 教程 入口

https://golang.org/doc/articles/wiki/

https://github.com/gin-gonic/gin

官网

https://golang.org/

sync.mutex Lock

go 复制代码
package main

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

// SafeCounter is safe to use concurrently.
type SafeCounter struct {
	mu sync.Mutex
	v  map[string]int
}

// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
	c.mu.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	c.v[key]++
	c.mu.Unlock()
}

// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
	c.mu.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	defer c.mu.Unlock()
	return c.v[key]
}

func main() {
	c := SafeCounter{v: make(map[string]int)}
	for i := 0; i < 1000; i++ {
		go c.Inc("somekey")
	}

	time.Sleep(time.Second)
	fmt.Println(c.Value("somekey"))
}
相关推荐
白衣鸽子3 分钟前
【基础数据篇】数据遍历大师:Iterator模式
后端·设计模式
用户4099322502126 分钟前
想抓PostgreSQL里的慢SQL?pg_stat_statements基础黑匣子和pg_stat_monitor时间窗,谁能帮你更准揪出性能小偷?
后端·ai编程·trae
啊森要自信13 分钟前
【GUI自动化测试】Python 自动化测试框架 pytest 全面指南:基础语法、核心特性(参数化 / Fixture)及项目实操
开发语言·python·ui·单元测试·pytest
xuejianxinokok13 分钟前
什么是代数类型 ? java为什么要添加record,Sealed class 和增强switch ?
后端·rust
洛小豆13 分钟前
Git打标签仓库看不到?她说:豆子,你又忘了加 --tags!
git·后端·github
赵谨言24 分钟前
基于python智能家居环境质量分析系统的设计与实现
开发语言·经验分享·python·智能家居
元亓亓亓36 分钟前
考研408--组成原理--day1
开发语言·javascript·考研·计组
LawsonJin40 分钟前
springboot实现微信小程序支付(服务商和普通商户模式)
spring boot·后端·微信小程序
Yurko1343 分钟前
【C语言】环境安装(图文)与介绍
c语言·开发语言·学习
仲星(._.)44 分钟前
C语言:字符函数和字符串函数
c语言·开发语言