Go में Concurrency

Go Channels

Send values between goroutines with channels: unbuffered, buffered, close and range.

  • उन्नत
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Send and receive
  • close and range
  • Buffered channels
Producer to main
  1. 1out <- messageproducer goroutine
  2. 2chan stringstep 1, step 2, step 3
  3. 3range messagesmain

A pipe between goroutines

A channel is a pipe that carries values from one goroutine to another. Sending and receiving wait for each other, so channels also keep goroutines in step.

out <- value sends and <-channel receives. An unbuffered channel hands each message directly to the receiver. close tells the receiver that nothing more will come, which ends the range loop. A buffered channel holds up to its capacity without a receiver.

मुख्य बातें

  1. ch <- v sends and <-ch receives.
  2. close ends a range loop.
  3. A buffered channel holds values without a receiver.

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

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

import "fmt"

func produce(steps int, out chan<- string) {
	for step := 1; step <= steps; step++ {
		out <- fmt.Sprintf("step %d done", step)
	}
	close(out) // tells the receiver there is nothing more
}

func main() {
	messages := make(chan string)
	go produce(3, messages)

	for message := range messages {
		fmt.Println("received:", message)
	}

	buffered := make(chan int, 2)
	buffered <- 1
	buffered <- 2
	fmt.Println(len(buffered), <-buffered, <-buffered)
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
received: step 1 done
received: step 2 done
received: step 3 done
2 1 2

अभ्यास

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

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

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

अगला: Select and Timeouts →

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

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

सभी चैलेंज