Skip to main content
← Back to Articles

*Go: Goroutines and Concurrency

Go: Goroutines and Concurrency

Modern applications often need to handle multiple operations at once: processing orders, querying databases, or serving concurrent HTTP requests. Executing these operations efficiently becomes increasingly important as workloads grow.

Go approaches this problem with goroutines, lightweight concurrent execution units managed by the Go runtime. Combined with channels and synchronization primitives, they provide a straightforward way to structure concurrent programs without manually managing an operating-system thread for every task.

To understand why this model works, let’s look at how goroutines execute, how they communicate, and how Go handles synchronization.

What is a goroutine?

A goroutine is lightweight unit of concurrent execution managed by the Go runtime. Contrary to traditional operating system threads, they don’t require a dedicated OS thread for every execution unit.

A goroutine starts with a small stack (usually around 2 KB) , which grows and shrinks dynamically as needed. This makes goroutines relatively inexpensive and allows applications to run large numbers of them.

Creating one is pretty direct: simply prefix a function call with the go keyword. The Go runtime takes care of scheduling goroutines onto available OS threads, managing their stacks, and coordinating their execution.

Think of goroutines as lightweight execution units that let you express concurrent work without manually managing OS threads.

For example:

golang
package main

import (
    "fmt"
    "time"
)

func sayHello() {
    fmt.Println("Hello from a goroutine!")
}

func main() {
    go sayHello()

    time.Sleep(time.Millisecond * 100)
}

The go keyword starts the function in a new goroutine, allowing the main function to continue executing independently.

In this example, time.Sleep simply keeps the main goroutine alive long enough for the other goroutine to execute. In real applications, synchronization mechanisms such as sync.WaitGroup are preferable to arbitrary sleeps.

How do goroutines communicate?

Go provides channels as a mechanism for goroutines to exchange data and synchronize their execution.

A channel is a typed communication outlet: it allows one goroutine to send values while another receives them.

There are two fundamental operations:

  • Sending data: ch <- value
  • Receiving data: val := <-ch

Channels preserve FIFO ordering of values, meaning values are received in the order they were sent. making the code predictable and executions easily trackable.

Creating a simple channel:

golang
ch := make(chan int)

Sending and receiving:

golang
ch <- 42

val := <-ch

Closing a channel:

golang
close(ch)

One important distinction is how channels handle blocking.

Unbuffered channels: A sender blocks until a receiver is ready, and a receiver blocks until a sender provides a value.

Buffered channels: A channel can hold a predefined number of values. A sender can continue sending without an immediate receiver as long as the buffer has available capacity.

For example:

ch := make(chan int, 3)

ch <- 10
ch <- 20
ch <- 30

value := <-ch

Here, the first three sends can complete without a receiver because the channel has a buffer capacity of three.

This blocking behavior is also what makes channels useful for synchronization, not just data transfer.

Safety and synchronization

Communication between goroutines requires synchronization to guarantee that data is transferred safely and that operations happen in the expected order.

Go channels provide synchronization guarantees through the Go memory model. For example, a channel send happens before the corresponding receive completes, making preceding writes visible to the receiving goroutine.

This helps coordinate concurrent operations without requiring explicit locks for every interaction.

However, channels aren’t a universal replacement for mutexes. When multiple goroutines need to access shared state, sync.Mutex and other synchronization primitives remain useful.

Let’s look at a practical example.

Example: A coffee shop ordering system

Imagine a coffee shop with three operators preparing orders simultaneously and one waiter collecting completed orders.

Each operator works independently, preparing three orders. Once an order is ready, the operator sends its order number through a shared channel. The waiter continuously receives completed orders and serves them.

golang
package main

import (
    "fmt"
    "sync"
    "time"
)

// operator goroutine preparing coffee orders.
func operator(id int, orderChannel chan<- int, wg *sync.WaitGroup) {
    defer wg.Done()

    for j := 1; j <= 3; j++ {
        orderNumber := (id * 10) + j

        fmt.Printf("☕ operator %d is brewing coffee order #%d...\n",
            id, orderNumber)

        // Simulate brewing time.
        time.Sleep(300 * time.Millisecond)

        // Send the completed order to the channel.
        orderChannel <- orderNumber
    }
}

func main() {
    waiterChannel := make(chan int)
    var wg sync.WaitGroup

    // Start three operator goroutines.
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go operators(i, waiterChannel, &wg)
    }

    // Close the channel once all operators finish.
    go func() {
        wg.Wait()
        close(waiterChannel)
    }()

    fmt.Println("--- Coffee shop is open! Waiting for orders... ---")

    // Waiter receives orders as they become available.
    for completedOrder := range waiterChannel {
        fmt.Printf("Waiter picked up and served order #%d!\n",
            completedOrder)
    }

    fmt.Println("--- All orders have been served! ---")
}

Understanding the execution

The application starts three independent operator goroutines. Each one prepares three orders, simulating the preparation time with time.Sleep.

Once an order is ready, its number is sent through waiterChannel.

Meanwhile, the main goroutine acts as the waiter, continuously receiving completed orders using a for range loop.

A sync.WaitGroup tracks the completion of all three operators. Once they finish their work, the channel is closed, allowing the receiver loop to terminate naturally.

The execution flow demonstrates several important concepts:

  • Concurrency: All three operators can make progress independently.
  • Communication: Completed orders are transferred through a shared channel.
  • Synchronization: The unbuffered channel coordinates sending and receiving.
  • Lifecycle management: sync.WaitGroup ensures all baristas finish before the channel is closed.

Notice that the order of completion isn’t guaranteed. An operator may finish an order before another , and the waiter serves orders as they become available.

The FIFO guarantee applies to values sent through the channel, not to the order in which goroutines execute or finish their work.

This is an important distinction: concurrency allows multiple operations to make progress independently, while synchronization coordinates how they interact.

Managing goroutines in production

Creating goroutines is easy, but managing their lifecycle and shared resources correctly is what makes concurrent applications reliable.

Go provides several synchronization and coordination mechanisms in its standard library

1. sync.WaitGroup

Allows a goroutine to wait until a collection of other goroutines finishes executing.

Useful when launching multiple independent operations that must all complete before continuing.

2. context.Context

Provides a mechanism to propagate cancellation signals, deadlines, and request-scoped values across goroutines and function calls.

Particularly useful in HTTP servers and distributed applications where operations should stop when a request is cancelled or a deadline expires.

3. sync.Mutex

Protects shared mutable state by ensuring that only one goroutine at a time can access a critical section protected by the same mutex.

Useful when multiple goroutines need to read or modify shared data.

4. select

Allows a goroutine to wait on multiple channel operations simultaneously.

It is particularly useful when coordinating concurrent tasks, handling cancellation signals, or implementing timeouts.

5. Go race detector

Go provides a built-in race detector that helps identify data races during execution.

You can enable it using:

golang
go test -race ./...

A data race occurs when multiple goroutines access the same memory concurrently, at least one access is a write, and the accesses aren’t properly synchronized.

The race detector is a valuable tool for catching these problems before they reach production.

How does Go compare to other languages?

Different languages provide different abstractions for concurrent execution. Java, C#, and Go all support concurrency, but differ in how they structure execution, synchronization, and communication.

Java

Java traditionally relies on OS-backed platform threads, with shared memory as its primary communication model.

Developers use synchronization mechanisms such as:

  • synchronized blocks and methods.
  • ReentrantLock and ReadWriteLock.
  • volatile fields for memory visibility.
  • Atomic operations through java.util.concurrent.atomic.

Java 21 introduced virtual threads, which are lightweight threads managed by the JVM rather than directly mapped one-to-one to OS threads.

Virtual threads make it significantly easier to write highly concurrent applications using familiar blocking code, while retaining Java’s shared-memory model.

C# / .NET

.NET provides a task-based concurrency model built around the Task Parallel Library (TPL).

Its main abstractions include:

  • Task and ValueTask for representing asynchronous operations.
  • async and await for asynchronous programming.
  • ThreadPool for managing reusable worker threads.
  • lock, Monitor, and SemaphoreSlim for synchronization.
  • Interlocked for atomic operations.
  • System.Collections.Concurrent for thread-safe collections.

Unlike Go’s goroutine model, C# developers commonly structure asynchronous I/O around tasks and the async/await programming model.

Go

Go takes a different approach by making lightweight concurrent execution a fundamental part of the language.

Its main abstractions include:

  • Goroutines: Lightweight execution units managed by the Go runtime.
  • Channels: Typed communication mechanisms between goroutines.
  • sync package: Traditional synchronization primitives such as mutexes and wait groups.
  • select: Coordination between multiple channel operations.

Go’s concurrency philosophy is often summarized by the following principle:

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

This doesn’t mean Go eliminates shared memory or locks. Rather, it encourages developers to structure concurrent operations around communication when that makes the design clearer.

Java, C#, and Go all provide capable concurrency models. The difference is largely in the abstractions and programming patterns they encourage.

Conclusion

Goroutines make concurrent programming in Go accessible by providing lightweight execution units managed by the runtime. Channels offer a structured way to communicate and synchronize between them, while synchronization primitives provide the tools needed to manage shared state and coordinate execution.

The real strength of Go’s concurrency model isn’t that it eliminates complexity, but that it provides simple, composable building blocks for expressing concurrent workloads.

Understanding how these building blocks work together is essential to writing reliable and scalable Go applications.