Modern CPUs contain multiple physical cores. Multithreading allows your C++ program to execute multiple operations simultaneously in parallel, dramatically accelerating computational performance.
std::jthread#include <iostream>
#include <thread>
#include <chrono>
void heavyComputation(int workerId, int iterations) {
std::cout << "Worker " << workerId << " started on CPU core.\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "Worker " << workerId << " finished " << iterations << " tasks!\n";
}
int main() {
std::cout << "Hardware Cores Available: " << std::thread::hardware_concurrency() << "\n";
// C++20 std::jthread automatically joins on scope exit!
std::jthread t1(heavyComputation, 1, 5000);
std::jthread t2(heavyComputation, 2, 8000);
std::cout << "Main thread continuing other work...\n";
// Both t1 and t2 join safely and cleanly right here!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Protecting shared data from race conditions.
Lock-free hardware atomic variables.
Cooperative multitasking vs kernel threads.