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"))
}
相关推荐
Crossoads10 分钟前
【数据结构】排序算法---桶排序
c语言·开发语言·数据结构·算法·排序算法
扎克begod15 分钟前
JAVA并发编程系列(9)CyclicBarrier循环屏障原理分析
java·开发语言·python
青灯文案116 分钟前
SpringBoot 项目统一 API 响应结果封装示例
java·spring boot·后端
code bean23 分钟前
【C#基础】函数传参大总结
服务器·开发语言·c#
阳光阿盖尔32 分钟前
EasyExcel的基本使用——Java导入Excel数据
java·开发语言·excel
蔚一34 分钟前
Java设计模式—面向对象设计原则(三) -----> 依赖倒转原则DIP(完整详解,附有代码+案例)
java·开发语言·设计模式·intellij-idea·依赖倒置原则
liang899940 分钟前
SpringSecurity原理解析(七):权限校验流程
java·开发语言
LQS202040 分钟前
基于Python实现一个浪漫烟花秀
开发语言·python
QXH20000042 分钟前
数据结构—单链表
c语言·开发语言·数据结构
梅如你42 分钟前
python批量对遥感影像进行归一化与数据清洗
开发语言·python