英文:
How to get a response from the consumer in a producer / consumer scenario?
问题
我一直在尝试使用通道来构建一种生产者/消费者模式。我有一个requests
通道,许多生产者将请求推送到该通道,然后我有一个processRequests
函数来处理这些请求。
package main
var requests chan string
func processRequests() {
for {
request := <-requests
// 处理请求...
// 如何返回响应呢?
}
}
func main() {
requests = make(chan string)
go processRequests()
requests <- "doSomething"
requests <- "doSomethingElse"
requests <- "etc"
select {} // 永久阻塞
}
我想知道的是,一旦请求被满足,如何将响应发送回生产者(并确保发送给正确的生产者,因为可能有多个生产者)?基本上,如何使这个通道成为双向通道?
有什么想法吗?
英文:
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
得分: 1
你应该使用两个通道。尝试使用一个通道来实现可能会变得混乱。
关于生产者/消费者模式,有一个Google Sites 可能会有用。
为了让生产者知道消费者的响应,你可以使用一个结构体来表示响应:
type responseMessage struct {
Request string
Response string
}
var requests chan string
var responses chan *responseMessage
func processRequests() {
for {
request := <- requests
// 处理请求...
responses <- &responseMessage{request, "一些响应字符串"}
}
}
func processResponses() {
someResponseMessage := <- responses
if someResponseMessage.Request == "doSomething" {
// 做一些事情!
}
}
func main() {
requests = make(chan string)
responses = make(chan *responseMessage)
go processRequests()
go processResponses()
requests <- "doSomething"
requests <- "doSomethingElse"
requests <- "etc"
select {} // 永久阻塞
}
以上是翻译好的代码部分。
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论