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"))
}
相关推荐
August_._6 小时前
【MySQL】触发器、日志、锁机制 深度解析
java·大数据·数据库·人工智能·后端·mysql·青少年编程
Halo_tjn6 小时前
基于 Object 类及包装类的专项实验
java·开发语言·计算机
拾忆,想起6 小时前
超时重传 vs 快速重传:TCP双保险如何拯救网络丢包?
java·开发语言·网络·数据库·网络协议·tcp/ip·php
@老蝴6 小时前
Java EE - 线程的状态
开发语言·java-ee·intellij-idea
BingoGo6 小时前
15 个 Eloquent 高级技巧,瞬间提升你的 Laravel 应用性能
后端·php
budingxiaomoli6 小时前
多线程(一)
java·开发语言·jvm·java-ee
golang学习记6 小时前
用 Go + Redis + HTMX 手撸一个超快 URL 短链接服务 🚀
后端
codervibe6 小时前
Spring Boot 热启动配置实战:从手动重启到秒级反馈
spring boot·后端
skyeeeeee6 小时前
kubeadm安装k8s集群
后端·kubernetes
Yue丶越7 小时前
【C语言】深入理解指针(二)
c语言·开发语言·数据结构·算法·排序算法