【问题标题】:How to get a response from the consumer in a producer / consumer scenario?如何在生产者/消费者场景中获得消费者的响应?
【发布时间】:2014-01-21 17:40:28
【问题描述】:

我一直在尝试使用渠道来构建某种生产者/消费者。我有一个requests 频道,许多生产者在其中推送请求,然后我有processRequests 处理这些请求。

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
}

我想知道的是,一旦请求得到满足,将响应发送回生产者(以及正确的,因为不止一个)的最佳方式是什么?基本上如何使它成为一个双向通道?

知道怎么做吗?

【问题讨论】:

  • Go 支持回调吗?
  • 发送一个请求数据元组和您希望收到响应的通道

标签: go channel goroutine consumer producer


【解决方案1】:

你真的应该使用两个渠道。试图让它与一个频道一起工作会很麻烦。

生产者/消费者模式中有一个Google Sites 可能有用。

为了让生产者知道消费者在响应什么,您可以使用一个结构来响应:

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多