除了一个运行之外,如何阻止所有goroutine

Fat*_*lan 1 go

我有两个(但后来我将是三个)去处理来自远程服务器(来自ampq通道)的传入消息的例程.但是因为它们正在处理相同的数据/状态,所以我想阻止所有其他的例程,除了正在运行的例程.

我想出了一个解决方案,使用chan bool每个例程阻塞然后释放它的代码,代码如下:

package main

func a(deliveries <-chan amqp, handleDone chan bool) {
    for d := range deliveries {
        <-handleDone        // Data comes always, wait for other channels
        handleDone <- false // Block other channels

        // Do stuff with data...

        handleDone <- true // I'm done, other channels are free to do anything
    }
}

func b(deliveries <-chan amqp, handleDone chan bool) {
    for d := range deliveries {
        <-handleDone
        handleDone <- false
        // Do stuff with data...
        handleDone <- true
    }
}

func main() {
    handleDone := make(chan bool, 1)
    go a(arg1, handleDone)
    go b(arg2, handleDone)
    // go c(arg3, handleDone) , later

    handleDone <- true // kickstart
}
Run Code Online (Sandbox Code Playgroud)

但是这个函数第一次会得到handleDone <- true,它们将被执行.后来如果再添加第三个函数,事情会变得更复杂.除了正在运行之外,如何阻止所有其他的例行程序?其他更好的解决方案?

Dan*_*iel 5

您想查看同步包.

http://golang.org/pkg/sync/

您可以使用互斥锁执行此操作.