0Pricing
C++ Academy · Lesson

std::thread Joining and Detaching

Spawn threads with std::thread and choose between join and detach.

The std::thread Class

The <thread> header introduced threading to the standard library in C++11. Each std::thread instance represents one OS thread.

Spawning a Thread

Pass a callable (function, lambda, functor) to the constructor. The thread starts running immediately.

#include <thread>
#include <iostream>

void worker() { std::cout << "running on thread\n"; }

int main() {
    std::thread t(worker);
    t.join();    // wait for it to finish
}

All lessons in this course

  1. std::thread Joining and Detaching
  2. std::mutex lock_guard and unique_lock
  3. Condition Variables and Worker Patterns
  4. std::async and std::future Basics
← Back to C++ Academy