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

标签 go concurrency

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

什么时候最好使用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/

相关文章:

go - 在 GCP Container-Optimized OS 上构建 go 可执行文件的 GOOS 和 GOARCH 值是多少

java - java中的CountDownLatch有什么意义?

java - 在 Spring MVC 请求处理程序中调用 Thread.currentThread().sleep(2000) 的第二个请求有什么影响?

Java - 在使用 JButton 执行时暂停线程池

postgresql - Postgres 中的 Go 和 IN 子句

mysql - 在 Go 中使用 now() 插入日期时间

Haskell 并发 IO 行为

java - 如何消除java动画闪烁

Go 编译已声明但未使用

在 go 中解析 set-cookie header