What are Goroutines?
A goroutine is a lightweight thread managed by the Go runtime. You can start thousands of goroutines simultaneously — they are much cheaper than OS threads.
package main
import (
"fmt"
"time"
)
func sayHello(name string) {
fmt.Println("Hello,", name)
}
func main() {
go sayHello("Alice") // runs concurrently
go sayHello("Bob")
time.Sleep(100 * time.Millisecond) // wait for goroutines
}
Channels
Channels are the pipes that connect goroutines. You can send values into a channel from one goroutine and receive them in another:
ch := make(chan int)
go func() {
ch <- 42 // send value
}()
value := <-ch // receive value
fmt.Println(value) // 42
Buffered Channels
ch := make(chan string, 3) // buffer size 3
ch <- "first"
ch <- "second"
ch <- "third"
fmt.Println(<-ch) // first
fmt.Println(<-ch) // second
Select Statement
ch1 := make(chan string)
ch2 := make(chan string)
go func() { ch1 <- "one" }()
go func() { ch2 <- "two" }()
select {
case msg1 := <-ch1:
fmt.Println("Received from ch1:", msg1)
case msg2 := <-ch2:
fmt.Println("Received from ch2:", msg2)
}
WaitGroup — wait for goroutines
import "sync"
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Println("Worker", id, "done")
}(i)
}
wg.Wait() // blocks until all goroutines finish
fmt.Println("All workers done")