gpt4 book ai didi

go - 什么时候应该在 channel 上使用互斥体?

转载 作者:IT王子 更新时间:2023-10-29 01:57:31 25 4
gpt4 key购买 nike

在过去的几周里,我一直在努力解决一个(不太)简单的问题:

什么时候最好使用sync.Mutex,相反,什么时候最好使用chan

似乎对于很多问题,两种策略都可以互换 - 这就是问题所在!

this video在 Golang 文档中找到。下面,我冒昧地在 playground 中口述代码,并将其转换为等效的 sync.Mutex

在现实世界中是否存在某个问题需要使用另一个?

注意事项:

  • 我是this use of chan的忠实粉丝并努力想出使用 sync.Mutex 的更优雅的实现方式。
  • 值得注意的是,chan 实现同时执行更多工作(达到 12 个)*

Playground :

chan 乒乓球:

package main

import (
"fmt"
"time"
)

type Ball struct { hits int }

func main() {
table := make(chan *Ball)
go player("ping", table)
go player("pong", table)

table <- new(Ball)
time.Sleep(1 * time.Second)
<-table
}

func player(name string, table chan *Ball) {
for {
ball := <-table
ball.hits++
fmt.Println(name, ball.hits)
time.Sleep(100 * time.Millisecond)
table <- ball
}
}

使用 sync.Mutex 乒乓球:

package main

import (
"fmt"
"time"
"sync"
)

type Ball struct { hits int }

var m = sync.Mutex{}

func main() {
ball := new(Ball)
go player("ping", ball)
go player("pong", ball)

time.Sleep(1 * time.Second)
}

func player(name string, ball *Ball) {
for {
m.Lock()
ball.hits++
fmt.Println(name, ball.hits)
time.Sleep(100 * time.Millisecond)
m.Unlock()

}
}

最佳答案

在 Go 中, channel 非常棒,您可以使用它们在 goroutine 之间进行通信。但是,为了方便起见,您可能希望在某些情况下使用 sync.Mutex。这些情况如下:

  • 保护内部状态
  • 缓存问题
  • 为了更好的表现

这是三个examples and explanations

  1. 一个简单的计数器

enter image description here

  1. 乒乓球比赛

enter image description here

  1. 最简单的缓存

enter image description here

关于go - 什么时候应该在 channel 上使用互斥体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47312029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com