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"))
}
相关推荐
Fighting_p18 分钟前
【预览word文档】使用插件 docx-preview 预览线上 word 文档
开发语言·c#·word
superman超哥27 分钟前
Rust 发布 Crate 到 Crates.io:从本地到生态的完整旅程
开发语言·后端·rust·crate·crates.io
浪客川28 分钟前
【百例RUST - 002】流程控制 基础语法练习题
开发语言·rust
一路往蓝-Anbo31 分钟前
C语言从句柄到对象 (二) —— 极致的封装:不透明指针与 SDK 级设计
c语言·开发语言·数据结构·stm32·单片机·嵌入式硬件
上天_去_做颗惺星 EVE_BLUE35 分钟前
C++学习:学生成绩管理系统
c语言·开发语言·数据结构·c++·学习
雪域迷影37 分钟前
使用Python库获取网页时报HTTP 403错误(禁止访问)的解决办法
开发语言·python·http·beautifulsoup·urllib
chao18984442 分钟前
基于Qt的SSH/FTP远程文件管理与命令执行实现方案
开发语言·qt·ssh
凯子坚持 c43 分钟前
Qt常用控件指南(1)
开发语言·数据库·qt
Flash.kkl1 小时前
Python基础语法
开发语言·python
十五年专注C++开发1 小时前
CMake进阶:find_package使用总结
开发语言·c++·cmake·跨平台编译