← C++ Index

🧵 <thread> — std::thread — Multi-threading (C++11)

C++11 portable threading library. Create threads with std::thread, protect shared data with std::mutex. Link with -pthread on Linux/macOS.

Include: #include <thread> | Namespace: std | Compile: g++ -Wall -std=c++17 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::threadclassRepresents a thread of execution
t.join()voidWait for thread t to finish
t.detach()voidLet thread run independently
t.joinable()boolTrue if thread can be joined/detached
t.get_id()thread::idReturn the thread's ID
std::this_thread::sleep_for(dur)voidSleep current thread for duration
std::mutexclassMutual exclusion lock
m.lock()voidAcquire the mutex (blocks)
m.unlock()voidRelease the mutex
m.try_lock()boolNon-blocking try to acquire
std::lock_guard<mutex>classRAII lock — unlocks on destruct
std::unique_lock<mutex>classFlexible RAII lock
std::condition_variableclassBlock threads until a condition is met
cv.wait(lk, pred)voidWait until pred() returns true
cv.notify_one()voidWake one waiting thread
cv.notify_all()voidWake all waiting threads
std::atomic<T>classLock-free atomic operations (needs <atomic>)

💡 Example Program

Copy, save as demo.cpp, and compile with the command at the bottom.

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
using namespace std;

mutex cout_mx, cnt_mx;
int shared_counter = 0;

void worker(int id, int n) {
    for (int i = 0; i < n; i++) {
        lock_guard<mutex> lg(cnt_mx);
        shared_counter++;
    }
    lock_guard<mutex> lg(cout_mx);
    cout << "Thread " << id << " done.\n";
}

int main() {
    const int N = 4;
    vector<thread> threads;
    for (int i = 0; i < N; i++)
        threads.emplace_back(worker, i + 1, 50);
    for (auto &t : threads) t.join();
    cout << "Final counter = " << shared_counter
         << " (expected " << N * 50 << ")\n";
    return 0;
}
// Compile: g++ -Wall -std=c++17 -pthread -o thread_demo thread_demo.cpp

← <stdexcept>  |  🏠 Index  |  <functional> →