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"))
}
相关推荐
想不到一个好的ID几秒前
Redis 哨兵(Sentinel)
后端
想不到一个好的ID33 分钟前
Redis 高可用:主从复制详解
后端
无限聚核37 分钟前
PHP 对接美团、抖音团购核销接口:预核销、核销、重试和撤销一份代码跑通,无限聚核
开发语言·php·美团·团购核销接口
源码_空间1 小时前
基于Springboot的在线编程练习判题平台(源码+文档)
java·spring boot·后端
码事漫谈1 小时前
当了领导才知道,有些时候,骂人的话真的忍不住
后端
程序员cxuan2 小时前
再见 Claude,国模 SOTA 模型来了
人工智能·后端·程序员
程序员cxuan2 小时前
夯爆了,影视界的 Codex 来了!
人工智能·后端·程序员
孟健2 小时前
抖音官方 CLI 上线:一句话搜同行爆款、扒文案,实测全记录
后端·ai编程
向科→向总工→空间动态计系统2 小时前
动态零轴融合三铁律
大数据·开发语言·人工智能·python·机器人
烬中寻道3 小时前
GoFrame + Trae:把数据库凭据从配置文件里彻底拿掉
后端