Sobes.tech
Junior

What is the difference between concurrency and parallelism?

sobes.tech AI

Answer from AI

Concurrency is a property of a system to solve multiple tasks simultaneously. This does not necessarily mean executing tasks at the same exact moment in time. On a single processor core, concurrency can be achieved through task switching (alternation).

Parallelism is a property of a system to execute multiple tasks at the same exact moment in time. This requires multiple processor cores or multiple processors.

Property Concurrency Parallelism
Goal Handle a large number of tasks Quickly perform many tasks
Execution Alternation (on one core) or parallel (on multiple cores) Simultaneously (on multiple cores)
Requirements Can be achieved on a single core Requires multiple cores or processors
Example Goroutines in Go Executing goroutines on different CPU cores

Concurrency is facilitating the solution of many tasks "simultaneously," whereas parallelism is actually executing many tasks "at the same time." Go supports both: goroutines provide concurrency, and the Go scheduler can distribute them across available cores to achieve parallelism.

// Example of concurrency (on one core)
func printA() {
  for i := 0; i < 5; i++ {
    println("A")
  }
}

func printB() {
  for i := 0; i < 5; i++ {
    println("B")
  }
}

func main() {
  go printA() // Goroutine 1
  go printB() // Goroutine 2
  // The Go scheduler can switch between printA and printB
  // on a single core, creating the illusion of simultaneous execution.
  // time.Sleep(time.Second) // Give time for goroutines to finish
}
// Example of potential parallelism (on multiple cores)
// If multiple CPU cores are available, the Go scheduler can
// run printA on one core and printB on another
// simultaneously.
func printA() {
  for i := 0; i < 5; i++ {
    println("A")
  }
}

func printB() {
  for i := 0; i < 5; i++ {
    println("B")
  }
}

func main() {
  //runtime.GOMAXPROCS(2) // Set the number of cores to use
  go printA() // Goroutine 1
  go printB() // Goroutine 2
  // If multiple cores are available, these goroutines can run in parallel
  // time.Sleep(time.Second) // Give time for goroutines to finish
}