PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to get a response from the consumer in a producer / consumer scenario?

 September 20, 2022     channel, consumer, go, goroutine, producer     No comments   

Issue

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?


Solution

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
}


Answered By - Tyson
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing