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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置