如何使用Go语言的goroutine、select和if语句来返回结果?

huangapple go评论66阅读模式
英文:

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 &lt;- num
}

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

func main() {
	for i := 0; i &lt; 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, &quot;hello from&quot;, msg)
      return
 }else {
      // not my number, put it back in the channel
      jr &lt;- 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.

huangapple
  • 本文由 发表于 2016年4月13日 20:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/36598819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定