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"))
}
相关推荐
Gopher_HBo9 小时前
Go语言加密算法
后端
在坚持一下我可没意见9 小时前
Python 修仙修炼录 08:字典秘境,参悟键值玄机
开发语言·笔记·python·入门·字典
青云计划9 小时前
数据库的守护者-单飞锁
后端
luck_bor9 小时前
Map&Stream流
java·开发语言
神奇小汤圆9 小时前
每次重启能救下几十万个请求:Cloudflare 如何用 Rust 实现零停机升级
后端
阿文的代码库9 小时前
如何在C++中使用标准库的智能指针
开发语言·c++·算法
用户298698530149 小时前
Java 统计 Word 文档中的单词数量
java·后端
yujunl9 小时前
U9客开Demo代码中的错误
开发语言
郝学胜-神的一滴9 小时前
Qt 高级开发 008: 使用QSetting记住上次打开路径
开发语言·c++·qt·开源软件
_洋9 小时前
Three.js 着色器相关方法总结
开发语言·javascript·着色器