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/