Вопрос

I have two go routines:

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()
}

What is proper way to ensure that the critical sections in these routines always execute alternately?
In other words, CS1 should be executed only after CS2 and vice versa: CS1, CS2, CS1, CS2, CS1, etc.

Это было полезно?

Решение

If you are running the functions in different goroutines, I would suggest dual channels. It is like passing on a little bool-ball. Each function has a channel they listen on, and another channel where they pass on the ball once the critical section is done. Then you can be sure that, no matter when they are called, they will always run alternately.

This pattern also allows you to extend the cycle with f3, f4 ... as well.

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
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top