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()
}
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.
After postHandler
receives msg
from channel jr
, that value is not in the channel anymore for another postHandler
to find. Channels do not broadcast.
Either send the value back into the channel if it's not equal to num
or restructure your code entirely.