英文:
go - How to use golang goroutine, select and if statement to return?
问题
我正在尝试在goroutine中创建一个"if"语句。
问题:如何从10中得到10?
var jr = make(chan int, 10)
var clients = 10 // 客户端数量随时间变化
func rpcMethod(num int) {
time.Sleep(time.Duration(rand.Intn(int(time.Second))))
jr <- num
}
func postHandler(num int) {
// 等待RPC数据
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()
}
结果 2/10
- 5 hello from 5
- 2 hello from 2
英文:
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
答案1
得分: 2
好的,以下是翻译好的内容:
好的,有多个问题。
首先,它不起作用,因为当从通道中读取某个内容时,它会消失(它不是广播,只有一个线程可以读取消息)。
所以为了让你的代码伪工作,你可以这样做:
if msg == num {
fmt.Println(num, "hello from", msg)
return
}else {
// 不是我的数字,将其放回通道
jr <- num
}
你将得到预期的结果,但仍然存在一个问题:你的程序无法正确关闭。我猜这只是为了实验/学习目的,但在真实的程序中,你会使用完全不同的代码。如果你对另一个版本感兴趣,请告诉我。
英文:
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.
答案2
得分: 1
在postHandler
从通道jr
接收到msg
之后,该值不再存在于通道中,以供另一个postHandler
找到。通道不会广播。
如果该值不等于num
,要么将其发送回通道中,要么完全重构你的代码。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论