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"))
}
相关推荐
老华带你飞5 小时前
博物馆展览门户|基于Java博物馆展览门户系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
liulilittle5 小时前
FileStream C++
开发语言·c++·cocoa
It's now5 小时前
Spring Framework 7.0 原生弹性功能系统讲解
java·后端·spring
点PY5 小时前
C++ 中 std::async 和 std::future 的并发性
java·开发语言·c++
无限大65 小时前
Agent 入门科普:从"人工智障"到"数字打工人"的进化史
后端
不会代码的小猴5 小时前
C++的第九天笔记
开发语言·c++·笔记
一 乐5 小时前
人事管理系统|基于Springboot+vue的企业人力资源管理系统设计与实现(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·后端
SelectDB5 小时前
浙江头部城商行:每日 700 万查询、秒级响应,Apache Doris 查算分离架构破局资源冲突
数据库·后端·apache
CoderYanger5 小时前
Java SE——12.异常(≠错误)《干货笔记》
java·开发语言
Data_agent6 小时前
1688获得1688店铺所有商品API,python请求示例
java·开发语言·python