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"))
}
相关推荐
GoGeekBaird8 小时前
我开源了 BeeWeave,给 AI Agent 搭一个越用越懂你的知识创作台
后端·github
西门吹-禅10 小时前
java springboot N+1问题
java·开发语言·spring boot
skywalk816310 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
犀利豆11 小时前
AI in Harness(四)
人工智能·后端
Hui Baby11 小时前
Spring Security
java·后端·spring
IT笔记12 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
2zcode12 小时前
免费开源项目文档:基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn
逝水无殇12 小时前
C# 运算符重载详解
开发语言·后端·c#
苏三说技术13 小时前
2026编程圈很火的10个Skills
后端
TPBoreas13 小时前
配置信息防泄露方案:.env 环境隔离详解(dotenv-java)
java·开发语言