Threads in C++¶
#include <thread>
Creating Threads is Far Too Easy¶
void f() { ... }
std::thread t(f);
void f(int i) { ... }
std::thread t(f, 666);
std::thread t([](){ ... });
Looks all pretty familiar, no?
Joinable vs. Detached¶
Why wait for termination?
Wait for a calculation to finish
Distribute parallelizable algorithm over multiple CPUs
Graceful program termination
t.join();
Why detach a thread?
Background service thread ⟶ program lifetime
t.detach();
Cornercases in Thread Lifetime¶
What if the program terminates before a thread?
int main() { std::thread t([](){for(;;);}); }
On Linux, at least …
When a process terminates, all its threads terminate immediately
Can I terminate a thread without its cooperation?
In Linux, yes, theoretically
What happens with locked mutexes?
⟶ Cancellation hooks (hell!)
Portably, no!