Skip to content

std::thread (C++11)

In a Nutshell

A native thread wrapper provided by the C++ Standard Library. Creating an object immediately launches the underlying OS thread, enabling true multi-task concurrency.

#include <thread>

Core API Cheat Sheet

OperationSignatureDescription
Constructorthread() noexcept;Default constructor, does not associate with any thread
Constructortemplate< class Function, class... Args > explicit thread( Function&& f, Args&&... args );Constructs and immediately starts the thread
Destructor~thread();Must be joined or detached before destruction, otherwise calls std::terminate
Assignmentthread& operator=( thread&& other ) noexcept;Move assignment
Joinablebool joinable() const noexcept;Checks if the thread is joinable (i.e., associated with an active thread)
Joinvoid join();Blocks the current thread until the target thread finishes execution
Detachvoid detach();Detaches the thread from the thread object, allowing it to run independently in the background
Get IDid get_id() const noexcept;Returns the thread identifier
Hardware Concurrencystatic unsigned int hardware_concurrency() noexcept;Returns the number of concurrent threads supported by the implementation

Minimal Example

cpp
#include <iostream>
#include <thread>

void task(int n) {
    for (int i = 0; i < n; ++i)
        std::cout << "worker: " << i << "\n";
}

int main() {
    std::thread t(task, 3);
    t.join(); // 阻塞等待线程 t 执行完毕
    std::cout << "done\n";
}
// Standard: C++11

Embedded Applicability: High

  • Zero abstraction overhead; std::thread maps directly to underlying OS threads (such as RTOS tasks or POSIX pthreads)
  • hardware_concurrency() can be used to probe available core count at runtime to dynamically determine thread pool size
  • Combined with std::mutex and std::atomic, it can safely protect shared peripheral registers or global buffers
  • Note the OS thread stack overhead (typically several KB to tens of KB). On MCUs with extremely limited memory, we must precisely control the number of threads and stack size

Compiler Support

GCCClangMSVC
4.63.119.0

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05