Go में Concurrency

Goroutines and sync.WaitGroup

Start lightweight threads with the go keyword and wait for all of them to finish.

  • उन्नत
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • The go keyword
  • WaitGroup: Add, Done, Wait
  • Writing results safely
Five goroutines
  1. 1wg.Add(1)count one more
  2. 2go square(...)runs on its own
  3. 3wg.Done()finished
  4. 4wg.Wait()main continues

Work that runs at the same time

A goroutine is a function that runs at the same time as the rest of the program. Writing go before a call starts one. Goroutines are cheap, so a program can run thousands of them.

main does not wait for goroutines by itself, so a WaitGroup counts them: Add before starting, Done when one finishes and Wait to block until the count is zero. Each goroutine writes to its own position of results, so the output is always the same.

मुख्य बातें

  1. go f() starts f in a new goroutine.
  2. main does not wait by itself.
  3. wg.Wait blocks until every Done is called.

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

Go
कोड चलाएँ →
main.go
package main

import (
	"fmt"
	"sync"
)

func square(id int, results []int, wg *sync.WaitGroup) {
	defer wg.Done()
	results[id] = id * id
}

func main() {
	var wg sync.WaitGroup
	results := make([]int, 5)

	for id := 0; id < 5; id++ {
		wg.Add(1)
		go square(id, results, &wg)
	}

	wg.Wait() // block until every goroutine calls Done
	fmt.Println(results)
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
[0 1 4 9 16]

अभ्यास

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

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

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

अगला: Channels →

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

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

सभी चैलेंज