我一直在尝试使用渠道建立某种生产者/消费者。我有一个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
}
我想知道的是,一旦请求得到满足,将回复发送回制作人(以及正确的回复,因为不止一个)的最佳方法是什么?基本上如何使这成为双向通道?
知道如何做到这一点?
答案 0 :(得分: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
}