Sobes.tech
Middle

How does concurrency differ from parallelism?

sobes.tech AI

Answer from AI

Concurrency is the ability of a system to manage multiple tasks that can be partially executed simultaneously, switching between them. Parallelism is the simultaneous execution of multiple tasks on different processor cores.

In simpler terms, concurrency is about organizing work so that multiple tasks can progress, while parallelism is about executing these tasks at the same time.

In Go, concurrency is achieved using goroutines and channels, and parallelism occurs when these goroutines are actually executed simultaneously on different CPU cores.

Example of concurrency in Go:

package main
import (
    "fmt"
    "time"
)
func task(name string) {
    for i := 0; i < 3; i++ {
        fmt.Println(name, "step", i)
        time.Sleep(100 * time.Millisecond)
    }
}
func main() {
    go task("A")
    go task("B")
    time.Sleep(500 * time.Millisecond)
}

Here, tasks "A" and "B" are executed concurrently, switching between each other, and if run on a multi-core processor, they can be executed in parallel.