簡體   English   中英

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

[英]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 // 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()
}

結果2/10

  • 從5向5打招呼
  • 來自2的2個問候

postHandler從通道jr收到msg之后,該值不再存在於通道中,以供另一個postHandler查找。 頻道不廣播。

如果該值不等於num則將其發送回通道 ,或者完全重組代碼。

好的,有多個問題。

首先,它不起作用,因為當從通道中讀取某些內容時,它消失了(它不是廣播,只有一個線程可以讀取消息)。

因此,為了使您的代碼能夠偽工作,您可以執行以下操作:

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

您將獲得預期的結果,但是仍然存在問題:您的程序無法正確關閉。 我想這只是出於實驗/學習的目的,但是在實際程序中,您將使用完全不同的代碼。 告訴我是否有其他版本會讓您感興趣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM