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"))
}
相关推荐
爱上咖啡香30 分钟前
我给 Laravel AI 写了个千问驱动,文本、语音、图像、视频全打通
后端
杨文说AI与数字化37 分钟前
票种表重构复盘:把填数字改成规则可执行版本
后端
回家路上绕了弯1 小时前
什么是 Agent as a Service?把 AI Agent 变成可调用的服务
后端
金銀銅鐵2 小时前
一个 Java 文件实现《孫子兵法·始計篇》中英对照阅读器
java·后端·ai编程
qq_406981032 小时前
c++拷贝构造函数
开发语言·c++
爱喝雪碧的可乐2 小时前
MATLAB
开发语言·算法·matlab
FungLeo3 小时前
成为全栈·Go 后端篇·三轮代码审阅之后:把可读性和证据做成工程规则
golang·go·ast·静态检查·成为全栈·代码审阅
用户360055579003 小时前
Kestrel_VLLM - 34 · 批量 M 行:五个块、两种层型,与「退回去」的两个原语
后端
leo在掘金3 小时前
25.5k Star 的 DeepInfer 怎么扛住3万亿参数
后端·架构
Agent世界3 小时前
cookie 判据会撒谎:CDP 登录态保活的五个实测坑
后端·自动化运维