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 小时前
翻完 Pi 源码:它和 Codex、Claude Code 有何不同
开发语言·javascript·人工智能·程序人生
qq_4480111612 小时前
C语言中的变量和函数的定义与声明
android·c语言·开发语言
霸道流氓气质12 小时前
SpringBoot中通用工具类库(Utils)封装与使用实践
spring boot·后端·python
孫治AllenSun13 小时前
【DataX】生产环境搭建DataX集群案例
java·开发语言·jvm
c2385614 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
moonsims15 小时前
星闪在跨域无人化系统作用
开发语言·php
MemoleCard16 小时前
深度解析Java当中的锁机制
后端
wear工程师16 小时前
ThreadLocal 在线程池里为什么会串数据:别只会答内存泄漏
java·后端
Iruoyaoxh16 小时前
栈和队列~
java·开发语言