代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。