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

oro*_*rom 3 concurrency go goroutine

我有两个 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()
}
Run Code Online (Sandbox Code Playgroud)

确保这些例程中的关键部分始终交替执行的正确方法是什么?
换句话说,CS1 只能在 CS2 之后执行,反之亦然:CS1、CS2、CS1、CS2、CS1 等。

ANi*_*sus 5

如果您在不同的 goroutine 中运行函数,我建议使用双通道。这就像传递一个小布尔球。每个函数都有一个它们监听的通道,以及另一个在关键部分完成后传递球的通道。然后你就可以确定,无论何时调用它们,它们总是会交替运行。

此模式还允许您使用 f3、f4 ... 来延长周期。

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
}
Run Code Online (Sandbox Code Playgroud)