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"))
}
相关推荐
ServBay5 分钟前
AI 做的小工具,怎样交给同事用?
后端·aigc·ai编程
用户693717500138414 分钟前
AI 越强,为什么我们反而越来越担心失业?
前端·后端·github
饮水桶_T1 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
炸膛坦客1 小时前
单片机/C/C++八股:(三十四)C 语言函数参数入栈顺序
c语言·开发语言·c++
咖啡八杯2 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
码途行者2 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang
codeejun3 小时前
每日一Go·MySQL-20、SQL 性能调优实战总结
sql·mysql·golang
拖孩3 小时前
又又又用 AI 写了个小程序:我站起来猛蹬 AI,使劲薅羊毛
前端·后端·微信小程序
bufengwangluo3 小时前
企业上网行为管理:代理网关部署位置怎么选,策略怎么落
开发语言·php
北冥有鱼3 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端