Search⌘ K
AI Features

Solution: The Parallel Greeter

Explore how to create and manage multiple threads using std::jthread to greet users concurrently. Understand how threads execute functions in parallel, the impact on output order, and how thread destructors ensure synchronized completion before program exit.

We'll cover the following...
C++ 23
#include <iostream>
#include <thread>
// Function to be executed by each thread
void greetUser(int id) {
// The output order is not guaranteed because threads run concurrently
std::cout << "Hello from thread " << id << "!" << std::endl;
}
int main() {
std::cout << "Server starting...\n";
// Launch three threads in parallel
// We pass the function name and its argument to the constructor
std::jthread t1(greetUser, 1);
std::jthread t2(greetUser, 2);
std::jthread t3(greetUser, 3);
// When t1, t2, and t3 go out of scope here, their destructors
// automatically wait for the threads to finish (join)
return 0;
}
...