In C++, concurrency and parallelism are often used interchangeably, but they refer to different concepts. Understanding these differences is crucial for writing efficient multi-threaded programs.
Concurrency refers to the ability of a program to handle multiple tasks at once. These tasks can be part of the same process and may run on the same core.
Concurrency involves context switching, where the CPU switches between different tasks, giving the illusion that they are running simultaneously.
In a concurrent program, tasks may not necessarily execute at the same time, but they can start, run, and complete in overlapping periods.
Parallelism, on the other hand, is about performing multiple operations simultaneously. It requires multiple cores or processors.
Parallelism aims to speed up computations by dividing tasks into smaller sub-tasks that can be executed simultaneously on different cores. This reduces the total time required to complete a task.
Here’s a simple example to illustrate the difference.  Concurrency:
#include <iostream>
#include <thread>
void Task1() {
std::cout << "Task 1 running\\n";
}
void Task2() {
std::cout << "Task 2 running\\n";
}
int main() {
std::thread t1(Task1);
std::thread t2(Task2);
t1.join();
t2.join();
return 0;
}
Task 1 running
Task 2 running
Parallelism:
#include <iostream>
#include <vector>
#include <execution>
#include <algorithm>
void Log(int number) {
std::cout << "Number: " << number << '\n';
}
int main() {
std::vector<int> numbers{1, 2, 3, 4, 5};
std::for_each(
std::execution::par,
numbers.begin(),
numbers.end(),
Log
);
}
Number: 1
Number: 4
Number: 5
Number: 2
Number: 3
In the concurrency example, Task1
and Task2
can run on the same core, switching context. In the parallelism example, Log()
operations run simultaneously on multiple cores.
Understanding these differences helps you decide when to use concurrency (improving responsiveness) or parallelism (improving performance) in your programs.
Answers to questions are automatically generated and may not have been reviewed.
Multithreading in C++ standard library algorithms using execution policies