Concurrency ใน Go
Go context: Cancellation and Timeouts
Stop work that takes too long or is no longer needed with context.WithTimeout and WithCancel.
สิ่งที่คุณจะได้เรียนรู้
- context.WithTimeout
- ctx.Done()
- context.WithCancel
Timeout of 50 ms
5 ms of worknil, finished in time500 ms of workcontext deadline exceededafter stop()context canceledA cancellation signal passed down
A context carries a cancellation signal through your program. Functions that may take a long time accept a context and stop when it is cancelled or its deadline passes.
WithTimeout creates a context that is cancelled after 50 milliseconds. slowOperation waits for either its work or ctx.Done(), whichever comes first, and returns ctx.Err() when the context wins. WithCancel returns a function that cancels the context by hand.
ประเด็นสำคัญ
- A context is cancelled by a deadline or by hand.
ctx.Done()is a channel that closes on cancel.ctx.Err()says why.
ตัวอย่าง Go ที่รันได้
main.go
package main
import (
"context"
"fmt"
"time"
)
func slowOperation(ctx context.Context, duration time.Duration) error {
select {
case <-time.After(duration):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
fmt.Println("quick:", slowOperation(ctx, 5*time.Millisecond))
fmt.Println("slow:", slowOperation(ctx, 500*time.Millisecond))
manual, stop := context.WithCancel(context.Background())
stop()
fmt.Println("cancelled:", slowOperation(manual, time.Second))
}
quick: <nil>
slow: context deadline exceeded
cancelled: context canceledฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด