Goroutines & ChannelsBeginner
1Question 1 of 1
goHow do Goroutines and Channels enable concurrency in Go?
Explanation & Concept
Go implements concurrency through Communicating Sequential Processes (CSP): 'Do not communicate by sharing memory; instead, share memory by communicating.'
• **Goroutines**: Extremely lightweight threads managed by the Go runtime, starting with only ~2KB of stack space that grows and shrinks dynamically. • **Channels**: Typed conduits through which you can send and receive values with the `<-` operator, synchronizing execution without explicit mutex locks.
Code Example
go
package main
import (
"fmt"
"time"
)
func fetchWorker(id int, ch chan string) {
time.Sleep(50 * time.Millisecond) // Simulate network call
ch <- fmt.Sprintf("Result from worker %d", id)
}
func main() {
results := make(chan string, 3) // Buffered channel
for i := 1; i <= 3; i++ {
go fetchWorker(i, results) // Launch concurrent goroutines
}
for i := 1; i <= 3; i++ {
msg := <-results // Receive from channel
fmt.Println(msg)
}
}How It Works & Key Takeaways
Goroutines cost a fraction of OS threads. Launching hundreds of thousands of concurrent goroutines is standard practice in Go services.
Mock Test · 1 Questions · Optional
Ready for Structs & Interfaces?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions