go - 我们如何在 Go 中使用 channel 来代替互斥锁?

标签 go goroutine

channel 将通信(值的交换)与同步相结合,确保两个计算(goroutine)处于已知状态。

如何使用 Google Go 中的 channel 来执行互斥锁的功能?

package main

import "sync"

var global int = 0
var m sync.Mutex

func thread1(){
    m.Lock()
    global = 1
    m.Unlock()
}

func thread2(){
    m.Lock()
    global = 2
    m.Unlock()
}

func main(){
   go thread1()
   go thread2()
}

最佳答案

将 Channel 用作 Mutex 的示例:

package main

var global int = 0
var c = make(chan int, 1)

func thread1(){
    <-c // Grab the ticket
    global = 1
    c <- 1 // Give it back
}

func thread2(){
    <-c
    global = 2
    c <- 1
}

func main() {
   c <- 1 // Put the initial value into the channel
   go thread1()
   go thread2()
}

您也可以使用 chan struct{} 代替 chan int 来减少内存大小。进入它的值是 struct{}{}(类型 struct{} 和一个空的内容 {})。见 Ivan black's comment举个例子。

关于go - 我们如何在 Go 中使用 channel 来代替互斥锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3952061/

相关文章:

go - sync.Once 执行

go - 使用golang从字符串中删除VARIATION SELECTOR-16?

ffmpeg - 转码流的 MIME 类型

go - 最大 goroutine 数

go - 并行执行 DynamoDB 查询(全局二级索引的 BatchGetItems)

go - 如何获取整数常量的字节?

go - channel是否发送抢占点用于goroutine调度?

Golang goroutine 不能使用函数返回值

用于填充结构实例 slice 的 Goroutine

go - 选择 channel 时陷入死锁