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"))
}
相关推荐
小小晓.2 分钟前
C++小白记:vector
开发语言·c++·算法
小刘学技术13 分钟前
AI人工智能决策树分类器:原理、实现与应用
开发语言·人工智能·python·算法·决策树·机器学习·数据挖掘
脱胎换骨-军哥14 分钟前
C++ 嵌入式编程实例:从寄存器操作到底层驱动开发
开发语言·c++·驱动开发
月落归舟17 分钟前
谈谈SpringMVC底层原理
后端·springmvc
夕除20 分钟前
请求区别及app网站区别
后端
w1395485642230 分钟前
鸿蒙原生开发手记:徒步迹 - 图片加载与缓存优化
后端
鱼子星_34 分钟前
【C++】vector
开发语言·c++·笔记·stl
double_eggm36 分钟前
uniapp.3
开发语言·前端·javascript
白玉cfc38 分钟前
熟悉Objective-C
开发语言·ios·objective-c
程序员爱钓鱼1 小时前
Rust 数组 Array 详解:定义、访问、遍历与切片
后端·rust