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"))
}
相关推荐
布朗克1687 分钟前
Go 入门到精通-15-错误处理
开发语言·python·golang·错误处理
zzb158020 分钟前
Zed 配置 Swift / iOS 开发
开发语言·ios·swift
卷福同学35 分钟前
AI编程出海第一步:别急着写代码,先找到老外真正愿意付费的需求
人工智能·后端·面试
北冥you鱼2 小时前
Go-Ethereum (Geth) 最佳实践:从部署到生产环境优化
开发语言·后端·golang
程序员爱钓鱼4 小时前
Rust 函数与返回值详解:参数、表达式与返回类型
后端·rust
这不小天嘛9 小时前
JAVA八股——J集合篇
java·开发语言
AOwhisky9 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
喜欢的名字被抢了12 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi
遨游DATA14 小时前
Spring Boot 启动失败排查:如何区分多 Bean 冲突与清理阶段异常
java·spring boot·后端
IT_陈寒14 小时前
Java线程池这个坑我算是踩明白了
前端·人工智能·后端