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"))
}
相关推荐
NiNi_suanfa3 小时前
【Qt】Qt 批量修改同类对象
开发语言·c++·qt
码事漫谈3 小时前
【精华】C++成员初始化列表完全指南:为什么、何时以及如何正确使用
后端
小糖学代码3 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
码事漫谈3 小时前
C++ 强制类型转换:类型安全的多维工具
后端
Data_agent3 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
妖灵翎幺4 小时前
C++ 中的 :: 操作符详解(一切情况)
开发语言·c++·ide
Halo_tjn4 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
star _chen4 小时前
C++实现完美洗牌算法
开发语言·c++·算法
周杰伦fans4 小时前
pycharm之gitignore设置
开发语言·python·pycharm
RainbowSea5 小时前
github 仓库主页美化定制
后端