Concurrency versus parallelism
Concurrency versus parallelism
Concurrency organizes a program into independently progressing tasks. Parallelism means executing tasks at the same instant on different processing resources. A goroutine is a task scheduled by the Go runtime, not necessarily a dedicated OS thread. Two goroutines can make progress by interleaving on one logical processor. Neither concurrency nor parallelism guarantees a speedup.
package main
import ( "fmt" "runtime" "sync")
func main() { fmt.Println("sequential", 2*2+3*3) old := runtime.GOMAXPROCS(1) defer runtime.GOMAXPROCS(old) var wg sync.WaitGroup var a, b int wg.Add(2) go func() { defer wg.Done(); a = 2 * 2 }() go func() { defer wg.Done(); b = 3 * 3 }() wg.Wait() fmt.Println("concurrent", a+b)}go f() starts a goroutine. The two tasks write distinct variables; a WaitGroup waits for both completion signals before main reads them. Add registers the work, Done subtracts one, Wait blocks until the count reaches zero. GOMAXPROCS(1) limits simultaneous execution of Go code, not the number of goroutines or OS threads. Restore the previous process-wide setting after this isolated demonstration; do not change it casually inside a library.
Expected output:
sequential 13concurrent 13Inspect the execution limit
package main
import ( "fmt" "runtime")
func main() { old := runtime.GOMAXPROCS(2) defer runtime.GOMAXPROCS(old) fmt.Println(runtime.GOMAXPROCS(0)) fmt.Println(runtime.NumCPU() > 0)}GOMAXPROCS(0) reads the current limit without changing it. NumCPU reports usable logical CPUs as detected at startup in the tested version. A limit of two permits parallel Go execution but does not prove that two tasks actually ran in parallel. Defaults are version and environment dependent; this example sets the limit explicitly. Test throughput with a representative benchmark rather than inferring it from goroutine count.
Expected output:
2trueTry it locally
With GOMAXPROCS(1), launch two goroutines computing the lengths of "go" and "lesson" into separate variables. Wait for both and print their sum. Restore the old limit.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency foundations 01: Concurrency versus parallelism
Check the lesson objective before moving on.
Can two goroutines be concurrent with GOMAXPROCS(1)?
Does GOMAXPROCS(2) prove a speedup?