← Back to Go Course | Chapter 11: Concurrency | Lesson 8 of 8

context Package का उपयोग

context एक timer और एक stop button जैसा है जिसे आप एक साथ हर worker को सौंपते हैं, ताकि आप उन्हें सभी को एक जगह से 'अभी रुको' या 'तुम्हारा समय खत्म हो गया' बता सकें।
Syntax
go
ctx, cancel := context.WithCancel(parent)
defer cancel()

ctx, cancel := context.WithTimeout(parent, duration)

select {
case <-ctx.Done():
    // ctx.Err()
}

Creating a Context with a Timeout

context.WithTimeout एक context बनाता है जो दी गई duration बीतते ही अपने आप cancellation signal देता है, जो यह सीमित करने का standard तरीका है कि कोई operation कितनी देर चल सकता है।

Note: हमेशा returned cancel function को call करें (अक्सर defer के ज़रिए) context के resources को जल्दी release करने के लिए।

उदाहरण: Creating a Context with a Timeout

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"context"
	"fmt"
	"time"
)

// main is where the program starts running
func main() {
	// Short declaration: create ctx, cancel and infer the type
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
	// defer runs this call when the surrounding function returns
	defer cancel()

	select {
	case <-time.After(100 * time.Millisecond):
		fmt.Println("work finished")
	case <-ctx.Done():
		fmt.Println("cancelled:", ctx.Err())
	}
}

Manual Cancellation with WithCancel

context.WithCancel एक context plus एक cancel function return करता है जो, call होने पर, तुरंत ctx.Done() देख रहे हर listener को signal देता है, सिर्फ एक timeout नहीं बल्कि किसी दूसरे event के जवाब में काम रोकने के लिए उपयोगी।

उदाहरण: Manual Cancellation with WithCancel

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"context"
	"fmt"
)

// main is where the program starts running
func main() {
	// Short declaration: create ctx, cancel and infer the type
	ctx, cancel := context.WithCancel(context.Background())

	// Start this call in a new goroutine (runs concurrently)
	go func() {
		// Print the values followed by a newline
		fmt.Println("cancelling now")
		cancel()
	}()

	<-ctx.Done()
	// Print the values followed by a newline
	fmt.Println("received cancellation:", ctx.Err())
}

Passing Context to Functions

Idiomatic Go functions जिन्हें cancel या timeout होने की ज़रूरत पड़ सकती है अपने पहले parameter के रूप में एक context.Context accept करते हैं, callers को function की अपनी built-in timeout logic की ज़रूरत के बिना cancellation control करने देते हुए।

Note: Convention के अनुसार, ctx हमेशा पहला parameter होता है और कभी किसी struct के अंदर store नहीं होता।

उदाहरण: Passing Context to Functions

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"context"
	"fmt"
	"time"
)

// Define the function doWork
func doWork(ctx context.Context) {
	select {
	case <-time.After(50 * time.Millisecond):
		fmt.Println("work completed")
	case <-ctx.Done():
		fmt.Println("work cancelled:", ctx.Err())
	}
}

// main is where the program starts running
func main() {
	// Short declaration: create ctx, cancel and infer the type
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
	// defer runs this call when the surrounding function returns
	defer cancel()
	doWork(ctx)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. हर function के पहले parameter के रूप में explicitly इसे पास करने के बजाय किसी context को struct field के अंदर store करना, जैसा Go convention उम्मीद करता है।
  2. context.WithCancel/WithTimeout से returned cancel function call करना भूल जाना, context से जुड़े resources leak करते हुए।
  3. किसी लंबे समय तक चलने वाले goroutine के अंदर ctx.Done() को नज़रअंदाज़ करना, इसलिए context cancelled होने के बाद भी यह असल में कभी नहीं रुकता।
चैप्टर सारांश
  • context.Context API boundaries और goroutines में cancellation signals और deadlines ले जाता है।
  • context.WithTimeout और context.WithCancel एक derived context plus एक cancel function बनाते हैं।
  • किसी goroutine को cancellation notice करने और अपना काम जल्दी रोकने के लिए ctx.Done() पर select करना चाहिए।
  • Convention: context.Context को explicitly किसी function के पहले parameter के रूप में पास किया जाता है, ctx नाम से।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.