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"))
}
相关推荐
qq_25183645714 小时前
基于java 税务管理系统设计与实现
java·开发语言
LuminousCPP14 小时前
从零开始学 C++|系列开篇:从 C 到 C++ 的衔接之路
开发语言·c++·笔记
超梦dasgg14 小时前
Java 生产环境分布式定时任务全解(实战落地版)
java·开发语言·分布式
Legendary_00814 小时前
18-30W 便携照明设备 USB-C PD 升级:选型与设计要点
c语言·开发语言
破土士V14 小时前
Java基础知识集合
java·开发语言
keykey6.14 小时前
从感知机到神经网络:深度学习的起源
开发语言·人工智能·深度学习·机器学习
㳺三才人子14 小时前
初探 Flask-WTF
后端·python·flask·html5
ZC跨境爬虫14 小时前
跟着 MDN 学JavaScript day_5:技能测试——变量实战
java·开发语言·前端·javascript
星恒随风14 小时前
C++ 类和对象入门(一):从 class、访问限定符到 this 指针
开发语言·c++·笔记·学习·状态模式