zl程序教程

您现在的位置是:首页 >  后端

当前栏目

0113-Go-互斥锁

Go 互斥
2023-09-27 14:23:45 时间

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/mutexes

目标

使用 Go 语言的互斥锁。

示例

package main

import (
    "fmt"
    "sync"
)

type Container struct {
    mu       sync.Mutex
    counters map[string]int
}

func (c *Container) inc(name string) {

    c.mu.Lock()
    defer c.mu.Unlock()
    c.counters[name]++
}

func main() {
    c := Container{
        counters: map[string]int{"a": 0, "b": 0},
    }

    var wg sync.WaitGroup

    doIncrement := func(name string, n int) {
        for i := 0; i < n; i++ {
            c.inc(name)
        }
        wg.Done()
    }

    wg.Add(3)
    go doIncrement("a", 10000)
    go doIncrement("a", 10000)
    go doIncrement("b", 10000)

    wg.Wait()
    fmt.Println(c.counters)
}

总结

使用 Go 语言的互斥锁。

附录