Thread Creation & Management (std::thread)

🔴 Advanced

📖 Definition

Introduced in C++11, std::thread (in <thread>) manages execution threads. Threads must either be joined (t.join()) before destruction to wait for completion or detached (t.detach()) to run independently in the background; failing to do so causes std::terminate.

💡 Code Example

#include <iostream>
#include <thread>

void workerTask(int id) {
    std::cout << "Worker Thread " << id << " executing.\n";
}

int main() {
    std::thread t1(workerTask, 1);
    t1.join(); // Wait for t1 thread execution to finish
    std::cout << "Main thread finished.\n";
    return 0;
}