Understand the contract

A goroutine is a concurrently executing function started with go. Starting it does not wait for completion. When main returns, the program exits without waiting for other goroutines. Give concurrent work an explicit owner, completion signal and stopping condition rather than assuming that a quick function will finish in time.

This block introduces WaitGroup, channels, channel closure, select, context and mutexes. These primitives solve different coordination problems. Concurrency structures independent activities; it does not guarantee that they run simultaneously or improve speed. Begin with a correct sequential program and add concurrency for a demonstrated need.

Work through the example

The example creates an unbuffered channel and starts one goroutine that sends 42. main receives from the channel, waiting until the value can be transferred, then prints it. The rendezvous makes completion relevant to the program’s lifetime without relying on a sleep or scheduler timing.

package main

import "fmt"

func main() {
    result := make(chan int)
    go func() { result <- 42 }()
    fmt.Println(<-result)
}

Watch this boundary

Every started goroutine needs a way to finish. A goroutine blocked forever on a send whose receiver has gone away leaks work and resources. Adding a large channel buffer only delays some blocking problems. Later examples make cancellation visible to both senders and receivers.

Practice with a changed input

Remove the receive and observe that the program no longer waits for the result. Restore it, then write down which goroutine owns each send and receive before adding a second worker.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services