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"))
}
相关推荐
清空mega3 分钟前
C++中关于数学的一些语法回忆(2)
开发语言·c++·算法
Mr_Xuhhh24 分钟前
从理论到实践:深入理解算法的时间与空间复杂度
java·开发语言·算法
Lenyiin32 分钟前
《Python 修炼全景指南:一》从环境搭建到第一个程序
开发语言·python
码事漫谈1 小时前
AI提效,到底能强到什么程度?
前端·后端
IT_陈寒1 小时前
React hooks依赖数组这个坑差点把我埋了
前端·人工智能·后端
涛声依旧393161 小时前
Python项目实战:学生信息管理系统
开发语言·python·数据挖掘
RATi GORI1 小时前
springBoot连接远程Redis连接失败(已解决)
spring boot·redis·后端
阿祖zu1 小时前
内容创作 AI 透明化声明倡议与项目开源
前端·后端·github
企鹅的蚂蚁1 小时前
【ESP32-S3开发踩坑】C++野指针引发的LoadProhibited死机与CMake依赖锁死排查
开发语言·c++
XiaoQiao6669991 小时前
python 简单题目练手【详解版】【1】
开发语言·python