Golang - Concurrency - Concurrency vs Parallelism

Publish date: 2025-09-27
Tags: <a href="https://programmercave.com/tags/Go/">Go</a>

The Core Idea: What’s the Difference?

Imagine you’re a chef in a kitchen.

In short:


Concurrency in Go

Go is designed for concurrency. It has first-class support for goroutines, which are lightweight threads.

Code Example:

This code runs two tasks concurrently. They take turns running on a single CPU.

package main

import (
	"fmt"
	"time"
)

func task(name string) {
	for i := 1; i <= 3; i++ {
		fmt.Printf("%s: %d\n", name, i)
		time.Sleep(100 * time.Millisecond)
	}
}

func main() {
	go task("Task A") // Start a goroutine
	go task("Task B") // Start another goroutine

	// Wait for the goroutines to finish
	time.Sleep(500 * time.Millisecond)
	fmt.Println("All tasks done!")
}

Parallelism in Go

If you have a multi-core processor, Go can run your concurrent code in parallel.

Code Example:

By default, Go will use all available CPU cores. You can control this with runtime.GOMAXPROCS.

package main

import (
	"fmt"
	"runtime"
	"time"
)

func intensiveTask(name string) {
	// A simple, CPU-bound task
	sum := 0
	for i := 0; i < 1_000_000_000; i++ {
		sum += i
	}
	fmt.Printf("%s finished with sum: %d\n", name, sum)
}

func main() {
	// Use all available CPU cores
	fmt.Printf("Using %d CPU cores\n", runtime.NumCPU())

	go intensiveTask("Task 1")
	go intensiveTask("Task 2")

	// Give the tasks time to complete
	time.Sleep(5 * time.Second)
}

Key Takeaways for Your Interview

Feature Concurrency Parallelism
Analogy One person juggling multiple tasks. Multiple people working on tasks.
Goal To structure a program to handle many tasks. To speed up a program by doing work at the same time.
Requires A way to switch between tasks (like goroutines). A multi-core processor.
In Go Achieved with goroutines, even on one core. Achieved when goroutines run on multiple cores.

The most important thing to remember: You write concurrent code in Go. The Go runtime will execute it in parallel if you have the hardware for it.

Tags: <a href="https://programmercave.com/tags/Go/">Go</a>