1 Star 0 Fork 0

c01dface/s-go-example

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
mutexes.go 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
c01dface 提交于 2024-12-09 13:56 . add mutexes.go
package main
// For more complex state we can use a mutex to safely
// access data across multiple goroutines.
import (
"fmt"
"sync"
)
// Container holds a map of counters; since we want to update it
// concurrently from multiple goroutines, we add a Mutex to
// synchronize access. Note that mutexes must not be copied, so if
// this struct is passed around, it should be done by pointer.
type Container struct {
mu sync.Mutex
counters map[string]int
}
// Lock the mutex before accessing counters; unlock it at the end of
// the function using a defer statement.
func (c *Container) inc(name string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counters[name]++
}
func main() {
// Note that the zero value of a mutex is usable as-is, so no
// initialization is required here.
c := Container{
counters: map[string]int{
"a": 0, "b": 0,
},
}
var wg sync.WaitGroup
// This function increments a named counter in a loop
doIncrement := func(name string, n int) {
for i := 0; i < n; i++ {
c.inc(name)
}
wg.Done()
}
// Run several goroutines concurrently; note that they all access
// the same Container, and two of them access the same counter
wg.Add(3)
go doIncrement("a", 10000)
go doIncrement("a", 10000)
go doIncrement("b", 10000)
// Wait for the goroutines to finish
wg.Wait()
fmt.Println(c.counters)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/vmalloc/s-go-example.git
git@gitee.com:vmalloc/s-go-example.git
vmalloc
s-go-example
s-go-example
master

搜索帮助