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

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

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

最佳答案

如果您在不同的 goroutine 中运行函数,我建议使用双 channel 。这就像传递一个小 bool 球。每个功能都有一个他们监听的 channel ,以及另一个他们在关键部分完成后传递球的 channel 。然后你可以确定,无论何时调用它们,它们将始终交替运行。

此模式还允许您使用 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
}

关于concurrency - Go语言中临界区的交替执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18654457/

相关文章:

java - ArrayBlockingQueue - 如何 "interrupt"正在等待 .take() 方法的线程

c++ - 并发访问 Map C++ 中的不同键

javascript - Ajax并发

go - 如何轮询 GitHub 存储库以拉取更改

go - 死锁在goroutines中

c# - TPL 数据流在运行时中断 LinkTo()

go - 在 goroutines 中调用 C.malloc/C.free 时的内存泄漏

concurrency - 不同输入数据的 Goroutine 执行时间

其他语言的 Goroutine 类似物

go - 多个goroutine的调度