go – How to use golang goroutine, select and if statement to return?

Issue

I’m trying to make a “if” statement in goroutine.
Question: how to make 10 from 10?

var jr = make(chan int, 10)
var clients = 10 // The number of clients varies with time.

func rpcMethod(num int) {
    time.Sleep(time.Duration(rand.Intn(int(time.Second))))
    jr <- num
}

func postHandler(num int) {
    // wait RPC data
    for {
        select {
        case msg := <-jr:
            {
                if msg == num {
                    fmt.Println(num, "hello from", msg)
                    return
                }
            }
        }
    }
}

func main() {
    for i := 0; i < clients; i++ {
        go postHandler(i)
        go rpcMethod(i)
    }
    fmt.Scanln()
}

Result 2/10

  • 5 hello from 5
  • 2 hello from 2

Solution

Ok, there are multiple problems.

First and foremost, it does not work because when something is read from a channel, it disappears (it is not a broadcast, only one thread can read the message).

So in order for your code to pseudo-work, you could do this:

 if msg == num {
      fmt.Println(num, "hello from", msg)
      return
 }else {
      // not my number, put it back in the channel
      jr <- num
 }

You will ge the expected result, but there is still a problem: your program won’t shutdown properly. I guess this is only for experiment/learning purposes, but in a real program you would use a completely different code. Tell me if another version would interest you.

Answered By – Derlin

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.