Golang

Goroutines

A Goroutine is a lightweight thread managed by the Go runtime. They are significantly cheaper than traditional OS threads, allowing you to run thousands (or even millions) of them concurrently in a single application.

Creating a Goroutine

To start a new goroutine, you simply use the go keyword followed by a function call:

package main

import (
	"fmt"
	"time"
)

func printMessage(msg string) {
	for i := 0; i < 3; i++ {
		fmt.Println(msg)
		time.Sleep(100 * time.Millisecond)
	}
}

func main() {
	go printMessage("Hello from Goroutine!")
	printMessage("Hello from Main!")
}

Communication

Goroutines run in the same address space, so access to shared memory must be synchronized. However, the Go philosophy states:

“Do not communicate by sharing memory; instead, share memory by communicating.”

This is achieved using Channels, which allow Goroutines to safely send and receive data. If you are new to Go, start at the introduction.