Buffered Channels क्या हैं
In this page:
ch := make(chan type, capacity)
ch <- value
value := <-ch
Creating a Buffered Channel
किसी channel बनाते समय make को एक दूसरा argument पास करना इसे एक buffer देता है, उस क्षण receiver तैयार न होने पर भी उतनी values भेजने देते हुए।
उदाहरण: Creating a Buffered Channel
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2 // does not block: buffer has room for 2
fmt.Println(<-ch)
fmt.Println(<-ch)
}
Login to try C/C++/Java/PHP code in the editor
Blocking Once the Buffer Is Full
एक buffered channel unlimited नहीं है -- एक बार इसका buffer भर जाए, अगला send अब भी तब तक block करता है जब तक कोई receiver एक value निकालकर जगह खाली न कर दे।
उदाहरण: Blocking Once the Buffer Is Full
package main
import "fmt"
func main() {
ch := make(chan int, 1)
ch <- 10
go func() {
fmt.Println("received:", <-ch) // frees buffer space
}()
ch <- 20 // would block until the goroutine above receives
fmt.Println("done")
}
Login to try C/C++/Java/PHP code in the editor
Checking Length and Capacity
len(ch) आपको बताता है कि वर्तमान में buffer में कितनी values प्राप्त होने के इंतज़ार में बैठी हैं, जबकि cap(ch) आपको channel बनते समय सेट की गई buffer की total capacity बताता है।
उदाहरण: Checking Length and Capacity
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create ch and infer the type
ch := make(chan int, 3)
ch <- 1
ch <- 2
// Print the values followed by a newline
fmt.Println("len:", len(ch), "cap:", cap(ch))
}
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि एक buffered channel कभी block नहीं करता -- यह अब भी buffer भरने पर send पर, या खाली होने पर receive पर block करता है।
- असली production/consumption rate के बारे में सोचे बिना एक arbitrary buffer size चुनना, एक design समस्या हल करने के बजाय छुपाते हुए।
- किसी channel की capacity (cap) को इसमें वर्तमान में queued values की संख्या (len) के साथ confuse करना।
- make(chan Type, n) एक buffered channel बनाता है जो बिना किसी receiver तैयार हुए n तक values रख सकता है।
- किसी buffered channel पर एक send सिर्फ buffer भरने पर block करता है; एक receive सिर्फ खाली होने पर block करता है।
- len(ch) बताता है कि वर्तमान में कितनी values queued हैं; cap(ch) buffer की total capacity बताता है।
- Buffered channels थोड़ी अलग speeds पर चलने वाले producers और consumers को decouple करने में मदद करते हैं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: