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"))
}
相关推荐
笨鸟先飞的橘猫8 分钟前
c++面向对象编程
开发语言·c++
小玮看世界17 分钟前
[Python]自动驾驶感知与决策练习题 (1-10)
开发语言·python·自动驾驶
满栀58520 分钟前
原生JS + ECharts 多图表可视化实战:从业务实现到工程化优化
开发语言·javascript·echarts
PieroPC21 分钟前
Windows 驱动备份与恢复工具 CMD bat
后端
Csvn22 分钟前
📊 SQL 入门 Day 12: 窗口函数基础
后端·sql
玖石书1 小时前
ASP.NET Core 迁移至 Spring系列:编译生态篇
后端·spring·asp.net
Java技术小馆1 小时前
AI 如何理解对话
后端
小满zs1 小时前
Go语言第五章(数组和切片)
后端·go
熬夜苦读学习1 小时前
Qt-- 系统相关
开发语言·qt
弹简特1 小时前
【Java项目-企悦抽】11-用户与认证模块-实现用户登录03(结束登录功能)-完成测试+对接前端+登录拦截器
java·开发语言