目录

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"))
}
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
Doker 多克9 分钟前
Python-Django系列—部件
开发语言·python
余渔鱼112321 分钟前
ASP.NET CORE部署IIS的三种方式
后端·github·asp.net
江沉晚呤时24 分钟前
深入解析 ASP.NET Core 中的 ResourceFilter
开发语言·c#·.net·lucene
huangyuchi.27 分钟前
【C++11】Lambda表达式
开发语言·c++·笔记·c++11·lambda·lambda表达式·捕捉列表
XiaoyuEr_66881 小时前
如何创建一个C#项目(基于VS2022版)
开发语言·c#
嘻嘻嘻嘻嘻嘻ys1 小时前
《Spring Boot 3 + GraalVM原生镜像实战:云原生时代的毫秒启动与性能调优》
前端·后端
嘻嘻嘻嘻嘻嘻ys1 小时前
《Spring Boot 3.0×GraalVM:云原生时代的毫秒级启动实战革命》
前端·后端
嘻嘻嘻嘻嘻嘻ys1 小时前
《Vue 3.4响应式内核优化与WebAssembly性能突破实战指南》
前端·后端
绵阳的脑内SSD1 小时前
Redis 通用命令与keyspace
后端
嘻嘻嘻嘻嘻嘻ys1 小时前
《Spring Boot 3百万并发实战:基于JDK21虚拟线程的性能革新》
前端·后端