doubu1853 2016-04-13 12:44
浏览 120
已采纳

go-如何使用golang goroutine,select和if语句返回?

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
  • 写回答

2条回答 默认 最新

  • dongxiansi0158 2016-04-13 13:03
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记