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"))
}
相关推荐
kfaino5 小时前
码农的AI翻身(五)你好,我叫 Transformer
后端·aigc
Oneslide10 小时前
机械革命 单系统纯净重装Ubuntu(全盘覆盖,清空原有Windows)
后端
GetcharZp11 小时前
告别OOM!用Go+libvips实现30000×50000超大图片的流式瓦片服务
后端·go
IT_陈寒11 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户479492835691512 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
神奇小汤圆13 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L14 小时前
LangGraph入门学习资料
后端
神奇小汤圆14 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
后端
kfaino14 小时前
码农的AI翻身(四)你好,我叫 Attention
人工智能·后端
lwx5728014 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端