为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Go中使用频道代替互斥体?

如何在Go中使用频道代替互斥体?

Go
神不在的星期二 2021-04-08 14:15:04
通道将通信(值的交换)与同步相结合,以确保两个计算(goroutines)处于已知状态。如何使用Google Go中的频道执行互斥功能?package mainimport "sync"var global int = 0var m sync.Mutexfunc thread1(){    m.Lock()    global = 1    m.Unlock()}func thread2(){    m.Lock()    global = 2    m.Unlock()}func main(){   go thread1()   go thread2()}
查看完整描述

2 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

使用通道作为互斥对象的示例:


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{}{}(typestruct{}和一个空的content {})。有关示例,请参见Ivan black的评论。


查看完整回答
反对 回复 2021-04-26
  • 2 回答
  • 0 关注
  • 201 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信