Threads in C++

#include <thread>

Creating Threads is Far Too Easy

No parameterization
void f() { ... }
std::thread t(f);
std::bind?
void f(int i) { ... }
std::thread t(f, 666);
Lambdas
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

Synchronize caller with termination of t
t.join();

Why detach a thread?

  • Background service thread ⟶ program lifetime

Detach a thread
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!