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"))
}
相关推荐
迅猛龙办公室几秒前
Python函数实现反转一个只有3位数的整数
开发语言·前端·python
“AI国潮设计-小江”3 分钟前
《【AIGC实战】Python+SDXL批量生成“英歌舞树莓香草布丁”IP,附保持角色一致性的代码逻辑》
开发语言·人工智能·python·prompt·aigc
张张123y7 分钟前
后端第十三课:大模型评测(Evals)从 0 到 1——看完面试能讲明白
后端·面试·职场和发展·大模型评测·evals
闻缺陷则喜何志丹9 分钟前
【C++特性及类库】多线程
开发语言·c++·多线程·语言特性·系统库
dtq042421 分钟前
C++3 - 分支语句if和string变量
开发语言·c++·学习
jimy122 分钟前
c++类成员访问只看静态类型
开发语言·c++
1560820721936 分钟前
银河麒麟 Qt 可执行文件打包说明
开发语言·驱动开发·qt
小蒜学长39 分钟前
基于数据挖掘的京东商城商品推荐系统设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端·推荐系统·个性化推荐
SEO_juper40 分钟前
手写 llms.txt 验证器:让 AI 更愿意引用你的网站(GEO)
开发语言·人工智能·python·聚类·seo·独立站
CCCCCCCCharlie41 分钟前
从0到1:一个字节的磁盘之旅
linux·开发语言·c++