如何在生产者/消费者场景中获得消费者的响应?

我一直在尝试使用渠道来构建某种生产者/消费者。我有一个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

}

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


三国纷争
浏览 209回答 1
1回答

Smart猫小萌

你真的应该使用两个通道。试图让它与一个通道一起工作会很麻烦。生产者/消费者模式上有一个可能有用的Google 站点。为了让生产者知道消费者正在响应什么,您可以使用一个结构作为响应:type responseMessage struct {&nbsp; &nbsp; Request string&nbsp; &nbsp; Response string}var requests chan stringvar responses chan *responseMessagefunc processRequests() {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; request <- requests&nbsp; &nbsp; &nbsp; &nbsp; // Process request...&nbsp; &nbsp; &nbsp; &nbsp; responses <- &responseMessage{request, "some response string"}&nbsp; &nbsp; }}func processResponses() {&nbsp; &nbsp; someResponseMessage := <- responses&nbsp; &nbsp; if someResponseMessage.Request == "doSomething" {&nbsp; &nbsp; &nbsp; &nbsp; // do something!&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; requests = make(chan string)&nbsp; &nbsp; responses = make(chan *responseMessage)&nbsp; &nbsp; go processRequests()&nbsp; &nbsp; go processResponses()&nbsp; &nbsp; requests <- "doSomething"&nbsp; &nbsp; requests <- "doSomethingElse"&nbsp; &nbsp; requests <- "etc"&nbsp; &nbsp; select {} // Block forever}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go