go同步锁 sync mutex

简介: 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

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"))
}


相关文章
|
4月前
|
消息中间件 安全 数据库连接
并发编程的艺术:Go语言中的Sync包技巧
并发编程的艺术:Go语言中的Sync包技巧
47 0
|
9月前
|
Go
go的同步锁
在Go语言中,同步锁(sync.Mutex)是一种用于保护共享资源的机制。它通过提供两个方法Lock()和Unlock()来实现对共享资源的互斥访问。
40 0
|
5月前
|
Cloud Native 安全 测试技术
GO 语言处理并发的时候我们是选择sync还是channel
GO 语言处理并发的时候我们是选择sync还是channel
|
6月前
|
安全 Java Go
GO通道和 sync 包的分享
GO通道和 sync 包的分享
|
7月前
|
安全 Go 开发者
Go 语言使用标准库 sync 包的 mutex 互斥锁解决数据静态
Go 语言使用标准库 sync 包的 mutex 互斥锁解决数据静态
25 0
|
Kubernetes 安全 Go
GO并发之好用的sync包
GO并发之好用的sync包
|
存储 安全 Go
Go语言,sync包如何控制并发?
除了 channel 通道,还有 sync.Mutex、sync.WaitGroup 这些原始的同步机制来,更加灵活的实现数据同步和控制并发。
65 0
Go语言,sync包如何控制并发?
|
Go
Go 专栏|并发编程:goroutine,channel 和 sync
Go 专栏|并发编程:goroutine,channel 和 sync
128 0
Go 专栏|并发编程:goroutine,channel 和 sync
|
缓存 安全 算法
Go基础:channel、定时器、select、锁、sync、atomic
Go基础:channel、定时器、select、锁、sync、atomic
265 0
Go基础:channel、定时器、select、锁、sync、atomic
|
JavaScript Go