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"))
}
相关推荐
ID_180079054736 分钟前
基于 Python 的淘宝商品详情数据结构化解析:SKU、价格与库存字段提取
开发语言·数据结构·python
q***72197 分钟前
springBoot 和springCloud 版本对应关系
spring boot·后端·spring cloud
星释10 分钟前
Rust 练习册 82:Hamming与字符串处理
开发语言·算法·rust
时间不说谎11 分钟前
c/c++的语法糖
开发语言
Laughtin23 分钟前
终端Python环境的选择与切换
开发语言·python
百***812735 分钟前
【SpringBoot】SpringBoot中分页插件(PageHelper)的使用
java·spring boot·后端
百***864635 分钟前
SpringBoot中自定义Starter
java·spring boot·后端
q***071436 分钟前
VScode 开发 Springboot 程序
java·spring boot·后端
q***465236 分钟前
Spring中使用Async进行异步功能开发实战-以大文件上传为例
java·后端·spring
头发还在的女程序员1 小时前
基于JAVA语言的短剧小程序-抖音短剧小程序
java·开发语言·小程序