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"))
}
相关推荐
韶博雅2 分钟前
emcc24ai
开发语言·数据库·python
yongui4783419 分钟前
C# 与三菱PLC通讯解决方案
开发语言·c#
2501_9333295521 分钟前
技术架构深度解析:Infoseek舆情监测系统的全链路设计与GEO时代的技术实践
开发语言·人工智能·分布式·架构
Tong Z24 分钟前
常见的限流算法和实现原理
java·开发语言
凭君语未可27 分钟前
Java 中的实现类是什么
java·开发语言
wearegogog12330 分钟前
离散系统参数辨识与广义预测控制MATLAB实现
开发语言·matlab
史迪仔011232 分钟前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
IT_陈寒1 小时前
为什么我的Vite热更新老是重新加载整个页面?
前端·人工智能·后端