dpv46227 2013-09-06 09:29
浏览 19
已采纳

在Go语言中交替执行关键部分

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.

  • 写回答

1条回答 默认 最新

  • dsds661730652211 2013-09-06 09:45
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思