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.

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")
}

Screenshot 2024-10-21 at 12.16.22 PM.png