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"))
}
相关推荐
superman超哥19 小时前
派生宏(Derive Macro)的工作原理:编译时元编程的艺术
开发语言·rust·开发工具·编程语言·rust派生宏·derive macro·rust元编程
easyboot19 小时前
C#使用pythonnet简单示例
开发语言·python·c#
晚霞的不甘19 小时前
Flutter 布局核心:构建交互式文档应用
开发语言·javascript·flutter·elasticsearch·正则表达式
少控科技20 小时前
QT新手日记 030
开发语言·qt
小唐同学爱学习20 小时前
短链接修改之写锁
spring boot·redis·后端·mysql
小此方20 小时前
Re:从零开始的 C++ STL篇(三)string的疑难问题详细解析:深拷贝,写时拷贝,三个swap
开发语言·c++
Linux猿20 小时前
基于Python的图书管理系统(可执行源码+详细报告+详细注释+运行步骤)
开发语言·python·毕业设计·课程设计·管理系统·图书管理系统项目
lanbing20 小时前
在Mac OS系统中安装Go语言环境教程
开发语言·后端·golang
生活很暖很治愈20 小时前
Linux基础指令——【2】
linux·服务器·后端·ubuntu