Go में Concurrency

Go context: Cancellation and Timeouts

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

  • उन्नत
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • 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.

मुख्य बातें

  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.

चलने योग्य Go उदाहरण

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))
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
quick: <nil>
slow: context deadline exceeded
cancelled: context canceled

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज