Concurrency ใน Go
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
โจทย์ทั้งหมด