通道将通信(值的交换)与同步相结合,保证两个计算(goroutine)处于已知状态。
如何使用 Google Go 中的通道来执行互斥量的功能?
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 作为互斥体的示例:
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{}{}
(type struct{}
和一个空内容{}
). See 伊万·布莱克的评论 /questions/3952061/how-can-we-use-channels-in-go-in-place-of-mutex/3953027#comment94999147_3953027举个例子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)