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"))
}
相关推荐
superman超哥10 小时前
Rust 生命周期省略规则:编译器的智能推导机制
开发语言·后端·rust·编译器·rust生命周期·省略规则·智能推导
福楠10 小时前
C++ STL | 容器适配器
c语言·开发语言·数据结构·c++
踏浪无痕10 小时前
从需求到落地:我们是如何搭建企业知识库问答系统的
后端·ai编程
源代码•宸10 小时前
GoLang基础语法(go语言结构、go语言变量、go语言常量、go语言运算符)
开发语言·后端·golang
林恒smileZAZ10 小时前
前端技巧:检测到省略号文本自动显示 Tooltip
开发语言·前端·javascript
Zzz不能停10 小时前
阻止冒泡和阻止元素默认行为的区别
开发语言·前端·javascript
小白学大数据10 小时前
Redis 在定时增量爬虫中的去重机制与过期策略
开发语言·数据库·redis·爬虫
心在飞扬10 小时前
langchain学习总结-ChatMessage 组件学习笔记
后端
CoderCodingNo10 小时前
【GESP】C++五级真题(二分答案考点) luogu-P13013 [GESP202506 五级] 奖品兑换
开发语言·c++