Skip to content

Goroutines

Goroutines are a fundamental feature of the Go programming language that allow for concurrent execution of functions. They are lightweight threads managed by the Go runtime, making it easy to handle multiple tasks at the same time without the overhead of traditional threads.

  • Lightweight: Goroutines have a smaller memory footprint compared to traditional threads. You can run thousands of goroutines concurrently without significant overhead.

  • Concurrency: They enable concurrent programming, which allows multiple operations to run simultaneously, improving the efficiency of programs, especially in I/O-bound applications.

  • Simplicity: You start a goroutine by using the go keyword followed by a function call. For example:

    go
    Copy code
    go myFunction()
  • Scheduling: The Go runtime includes a built-in scheduler that handles the distribution of goroutines across available OS threads. This makes goroutines a powerful tool for managing concurrency without requiring complex thread management.

  • Communication: Goroutines communicate with each other using channels, which provide a way to send and receive values safely between them, facilitating synchronization

No goroutines

package main
import (
"fmt"
"time"
)
func expensiveOp(str string) {
for i := range 3 {
fmt.Println(str, "-", i)
}
}
func main() {
expensiveOp("first")
expensiveOp("second")
time.Sleep(time.Second * 2)
fmt.Println("Done")
}

With go routines

package main
import (
"fmt"
"time"
)
func expensiveOp(str string) {
for i := range 3 {
fmt.Println(str, "-", i)
}
}
func main() {
go expensiveOp("first")
go expensiveOp("second")
time.Sleep(time.Second * 2)
fmt.Println("Done")
}

Goroutines Example