Lập trình đồng thời trong Go

Go context: Cancellation and Timeouts

Stop work that takes too long or is no longer needed with context.WithTimeout and WithCancel.

  • Nâng cao
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • context.WithTimeout
  • ctx.Done()
  • context.WithCancel
Timeout of 50 ms
5 ms of worknil, finished in time
500 ms of workcontext deadline exceeded
after stop()context canceled

A 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.

Những điểm quan trọng

  1. A context is cancelled by a deadline or by hand.
  2. ctx.Done() is a channel that closes on cancel.
  3. ctx.Err() says why.

Ví dụ Go chạy được

Go
Chạy code →
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))
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
quick: <nil>
slow: context deadline exceeded
cancelled: context canceled

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách