Goroutines क्या हैं
go functionName(args)
go func() {
// body
}()
Starting a Goroutine
किसी function call को go keyword से prefix करना इसे एक goroutine के रूप में launch करता है, concurrent execution की एक lightweight, स्वतंत्र रूप से scheduled unit जो सीधे operating system के बजाय Go runtime द्वारा managed है।
उदाहरण: Starting a Goroutine
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("hello from a goroutine")
}
func main() {
go sayHello()
time.Sleep(50 * time.Millisecond) // give the goroutine time to run
fmt.Println("main finished")
}
Login to try C/C++/Java/PHP code in the editor
main() Doesn't Wait
Program main() के return होते ही बंद हो जाता है, चाहे इसके launch किए किसी goroutines ने खत्म किया हो या नहीं -- यही वजह है कि असली code को explicit synchronization चाहिए, सिर्फ यह उम्मीद नहीं कि चीज़ें 'काफी तेज़ी से' खत्म हो जाएंगी।
उदाहरण: main() Doesn't Wait
package main
import "fmt"
func main() {
done := make(chan bool)
go func() {
fmt.Println("goroutine work happening")
done <- true
}()
<-done // waits until the goroutine signals completion
fmt.Println("main continues only after goroutine finishes")
}
Login to try C/C++/Java/PHP code in the editor
Many Lightweight Goroutines
चूंकि goroutines एक पूरे OS thread के overhead के बजाय एक छोटे, बढ़ने योग्य stack (बस कुछ KB) से शुरू होते हैं, एक Go program आराम से उनमें से हज़ारों concurrently चला सकता है।
उदाहरण: Many Lightweight Goroutines
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"fmt"
"sync"
)
// main is where the program starts running
func main() {
// Declare wg with the zero value of its type
var wg sync.WaitGroup
// Loop: repeat while the condition holds
for i := 0; i < 5; i++ {
wg.Add(1)
// Start this call in a new goroutine (runs concurrently)
go func(n int) {
// defer runs this call when the surrounding function returns
defer wg.Done()
// Print the values followed by a newline
fmt.Println("worker", n, "done")
}(i)
}
wg.Wait()
}
Login to try C/C++/Java/PHP code in the editor
- एक goroutine launch करना और इसके खत्म होने से पहले main() को return होने देना, बिना किसी error के इसे बीच में चुपचाप मार देते हुए।
- यह मान लेना कि 'go func()' तुरंत और synchronously चलता है -- यह concurrently चलने के लिए scheduled है, बिना guaranteed start order के।
- यह भूल जाना कि बिना synchronization के data share करने वाले goroutines race कर सकते हैं, shared state को अप्रत्याशित रूप से corrupt करते हुए।
- go keyword किसी function call को एक नए, concurrently चलने वाले goroutine के रूप में launch करता है।
- Goroutines OS threads की तुलना में बेहद lightweight हैं -- हज़ारों एक साथ चल सकते हैं।
- main goroutine अपने आप दूसरे goroutines का इंतज़ार नहीं करता; main() return होने पर program exit हो जाता है।
- Goroutines को coordinate करने के लिए आमतौर पर channels या WaitGroup जैसे sync primitives चाहिए होते हैं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: