Appearance
Launching Threads
Multithreading allows you to run parts of your program simultaneously --- improving performance, responsiveness, and throughput.
Thread vs JThread
std::thread
The standard thread class allows you to spawn threads with a function pointer. Basic usage:
cpp
#include <thread>
#include <iostream>
void worker_function() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(worker_function); // Launch thread
t.join(); // Wait for completion
return 0;
}Key points:
- Manual joining required: You must call
join()ordetach()before the thread object is destroyed - Exception safety: If you don't join/detach,
std::terminate()is called and your program will crash prematurely
std::jthread (C++20)
C++20 introduces std::jthread, a.k.a. "joining thread" that automatically joins when it goes out of scope:
cpp
#include <thread>
#include <iostream>
void worker_function(std::string greeting) {
std::cout << greeting << " from jthread!" << std::endl;
}
int main() {
std::jthread t(worker_function, "Aloha"); // Launch thread
// Automatically joins when t goes out of scope
return 0;
}Why join?
Joining ensures that all work is done and the thread resources are properly released before proceeding. If you don't wish to wait for the thread to complete, you can detach it instead.
cpp
std::thread t(worker_function);
// Option 1: Join (wait for completion)
t.join(); // Main thread waits here
// Option 2: Detach (fire and forget)
t.detach(); // Thread runs independently, main continues immediatelyWhen to use each:
- Join: When you need the result or want to ensure completion
- Detach: For background tasks that don't affect main flow
Launch 3 threads that each call increment_counter function. Assume increment_counter counter takes no arguments and returns void.
cpp
#include <thread>
#include <iostream>
// void increment_counter();
void thread_spawn() {
// TODO: Create 3 threads that each call increment_counter function. Assume increment_counter
counter takes no arguments and returns void.
}