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"))
}
相关推荐
朦胧之12 分钟前
PostgreSQL 数据库笔记
人工智能·后端
xcLeigh29 分钟前
Go入门:整数类型的溢出与安全边界
java·安全·golang
LorryJovens1 小时前
【LAAP科研】CEN因果等价网络理论---从双缝干涉到因果等价
开发语言·php
Brilliantwxx1 小时前
【Linux】 进程(10) 进程控制深度解析:创建、终止与等待
linux·运维·服务器·c语言·开发语言·网络
卢锡荣2 小时前
国产PD3.1全集成Type-C管控芯片LDR6020P
c语言·开发语言
IT_陈寒2 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端
Freak嵌入式3 小时前
Pico UART 数据收发实战:硬件配置、MicroPython 编程
java·开发语言·单片机·嵌入式硬件·生活
Casual3 小时前
【网络基础进阶】:看懂子网划分与 VLAN
开发语言·网络·php
LucianaiB3 小时前
用 WorkBuddy 研究腾讯、阿里和 DeepSeek,我没敢直接说「AI 很赚钱」
后端
用户8356290780513 小时前
使用 Python 管理 PDF 属性和元数据
后端·python