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"))
}
相关推荐
神奇小汤圆1 分钟前
我研读了 500 个 Spring Boot 生产级代码库,90% 都犯了这 7 个致命错误
后端
空中海2 分钟前
03 MyBatis Spring Boot 集成、事务、测试与工程化体系
spring boot·后端·mybatis
ElonMuscle4 分钟前
GO环境速建笔记
后端
csgo打的菜又爱玩6 分钟前
11.JobManager 启动流程总结
大数据·开发语言·qt·microsoft·flink
用户2986985301410 分钟前
Java 从零生成 Word 文档:段落、图片与表格操作
java·后端
2401_8332693011 分钟前
Java IO流:从字节到字符的桥梁
java·开发语言
hhzz12 分钟前
第1天:初识Python
开发语言·python·学习编程
江沉晚呤时16 分钟前
C# 运行时类型创建:深入探索动态类型生成技术
开发语言·c#
SimonKing39 分钟前
OpenCode 在 IDEA 中使用 ACP 协议 VS 直接使用 TUI,哪个编程方式更是你的菜?
java·后端·程序员
Gopher_HBo40 分钟前
Disruptor多生产者多消费者分析
后端