1 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個贊
如果你在不同的 goroutines 中運(yùn)行這些函數(shù),我會建議雙通道。這就像傳遞一個小布爾球。每個函數(shù)都有一個他們監(jiān)聽的通道,以及另一個通道,一旦關(guān)鍵部分完成,他們就會將球傳給另一個通道。那么您可以確定,無論何時調(diào)用它們,它們始終會交替運(yùn)行。
此模式還允許您使用 f3、f4 ... 擴(kuò)展循環(huán)。
package main
func f1(do chan bool, next chan bool) {
//... some code
<-do // Waits for the ball
// critical section 1 (CS1)
//... critical section code
// end criticla section 1
next <- true // Pass on the ball to the next function
//... more code
}
func f2(do chan bool, next chan bool) {
//... some code
<-do
// critical section 2 (CS2)
//... critical section code
// end criticla section 2
next <- true
//... more code
}
func main() {
cf1 := make(chan bool, 1)
cf2 := make(chan bool, 1)
cf1 <- true // Let cf1 start with the ball
go f1(cf1, cf2)
go f2(cf2, cf1)
// Wait here, otherwise it will just exit
}
- 1 回答
- 0 關(guān)注
- 222 瀏覽
添加回答
舉報