doushenmao9036 2014-01-21 17:40
浏览 56
已采纳

在生产者/消费者场景中,如何从消费者那里得到回应?

I've been trying to use channels to build some kind of producer / consumer. I have a requests channel where the many producers push requests, then I have processRequests that handles the requests.

package main

var requests chan string

func processRequests() {
    for {
        request <- requests
        // Process request...
        // And return response - how?
    }
}

func main() {
    requests = make(chan string)

    go processRequests()

    requests <- "doSomething"
    requests <- "doSomethingElse"
    requests <- "etc"

    select {} // Block forever
}

What I'm wondering is what would be the best way to send back a response to the producer (and to the right one, since there's more than one), once the request is fulfilled? Basically how to make this a two way channel?

Any idea how it could be done?

  • 写回答

1条回答 默认 最新

  • doupin1073 2014-01-21 19:06
    关注

    You should really use two channels. Trying to make it work with one channel will be messy.

    There's a Google Sites on the Producer/Consumer pattern that may be useful.

    For the producer to know what the consumer is responding to, you could use a struct for the response:

    type responseMessage struct {
        Request string
        Response string
    }
    
    var requests chan string
    var responses chan *responseMessage
    
    func processRequests() {
        for {
            request <- requests
            // Process request...
            responses <- &responseMessage{request, "some response string"}
        }
    }
    
    func processResponses() {
        someResponseMessage := <- responses
        if someResponseMessage.Request == "doSomething" {
            // do something!
        }
    }
    
    func main() {
        requests = make(chan string)
        responses = make(chan *responseMessage)
    
        go processRequests()
        go processResponses()
    
        requests <- "doSomething"
        requests <- "doSomethingElse"
        requests <- "etc"
    
        select {} // Block forever
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛