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"))
}
相关推荐
「QT(C++)开发工程师」6 分钟前
C++ auto 用法详解
开发语言·c++
OPEN-F13 分钟前
C++STL教程:容器适配器与实用工具
开发语言·c++
yaoxin52112324 分钟前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F30 分钟前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++
有点。33 分钟前
C++二叉搜索树进阶
开发语言·c++
HugoStudio_SWAN37 分钟前
【擦除重绘】C++ 控制台动画:弹跳 Logo DVD 屏保效果
开发语言·c++·学习·程序人生
2601_962073812 小时前
Spring全面详解(基础版)
java·后端·spring
IT_陈寒2 小时前
Vite打包时的静态资源坑,我帮你踩过了
前端·人工智能·后端
考虑考虑2 小时前
kubectl命令
运维·后端·自动化运维
kyle~2 小时前
C++_STL---迭代器失效
开发语言·c++