Go में Concurrency
Go select and Timeouts
Wait on several channels at once, give up after a timeout, or check without waiting.
आप क्या सीखेंगे
- select with several cases
- time.After
- default
select
case <-fastready after 10 mscase <-slowready after 200 mscase <-time.After(50ms)timeoutThe first ready channel wins
select waits for the first of several channel operations that is ready. It is how a goroutine listens to more than one channel, adds a timeout, or checks a channel without waiting.
The first select receives from fast because it is ready first. In the second, time.After delivers a value after 50 milliseconds, before slow is ready, so the timeout case runs. A default case runs at once when no channel is ready.
मुख्य बातें
- select runs the first case that is ready.
time.Afteradds a timeout.- default runs when nothing is ready.
चलने योग्य Go उदाहरण
main.go
package main
import (
"fmt"
"time"
)
func main() {
fast := make(chan string)
slow := make(chan string)
go func() {
time.Sleep(10 * time.Millisecond)
fast <- "fast result"
}()
go func() {
time.Sleep(200 * time.Millisecond)
slow <- "slow result"
}()
select {
case message := <-fast:
fmt.Println(message)
case message := <-slow:
fmt.Println(message)
}
select {
case message := <-slow:
fmt.Println(message)
case <-time.After(50 * time.Millisecond):
fmt.Println("timed out waiting for slow")
}
ready := make(chan int)
select {
case value := <-ready:
fmt.Println(value)
default:
fmt.Println("nothing ready, moving on")
}
}
fast result
timed out waiting for slow
nothing ready, moving onअभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज