[英]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()
}
好的,有多個問題。
首先,它不起作用,因為當從通道中讀取某些內容時,它消失了(它不是廣播,只有一個線程可以讀取消息)。
因此,為了使您的代碼能夠偽工作,您可以執行以下操作:
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.