Go 语言中临界区的交替执行

我有两个 go 例程:


func f1 { 

    ... some code 


    // critical section 1 (CS1)     

        ... critical section code                                   

    // end criticla section 1


    ... more code

}


func f2 { 

    ... some code 


    // critical section 2 (CS2)    

        ... critical section code                                

    // end criticla section 2


    ... more code

}


func main() {

   go f1()

   go f2()

}

确保这些例程中的临界区始终交替执行的正确方法是什么?

换句话说,CS1 应该只在 CS2 之后执行,反之亦然:CS1、CS2、CS1、CS2、CS1 等。


尚方宝剑之说
浏览 203回答 1
1回答

一只斗牛犬

如果你在不同的 goroutines 中运行这些函数,我会建议双通道。这就像传递一个小布尔球。每个函数都有一个他们监听的通道,以及另一个通道,一旦关键部分完成,他们就会将球传给另一个通道。那么您可以确定,无论何时调用它们,它们始终会交替运行。此模式还允许您使用 f3、f4 ... 扩展循环。package mainfunc f1(do chan bool, next chan bool) {&nbsp; &nbsp; &nbsp; &nbsp; //... some code&nbsp; &nbsp; &nbsp; &nbsp; <-do // Waits for the ball&nbsp; &nbsp; &nbsp; &nbsp; // critical section 1 (CS1)&nbsp; &nbsp; &nbsp; &nbsp; //... critical section code&nbsp; &nbsp; &nbsp; &nbsp; // end criticla section 1&nbsp; &nbsp; &nbsp; &nbsp; next <- true // Pass on the ball to the next function&nbsp; &nbsp; &nbsp; &nbsp; //... more code}func f2(do chan bool, next chan bool) {&nbsp; &nbsp; &nbsp; &nbsp; //... some code&nbsp; &nbsp; &nbsp; &nbsp; <-do&nbsp; &nbsp; &nbsp; &nbsp; // critical section 2 (CS2)&nbsp; &nbsp; &nbsp; &nbsp; //... critical section code&nbsp; &nbsp; &nbsp; &nbsp; // end criticla section 2&nbsp; &nbsp; &nbsp; &nbsp; next <- true&nbsp; &nbsp; &nbsp; &nbsp; //... more code}func main() {&nbsp; &nbsp; cf1 := make(chan bool, 1)&nbsp; &nbsp; cf2 := make(chan bool, 1)&nbsp; &nbsp; cf1 <- true // Let cf1 start with the ball&nbsp; &nbsp; go f1(cf1, cf2)&nbsp; &nbsp; go f2(cf2, cf1)&nbsp; &nbsp; // Wait here, otherwise it will just exit}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go