输入关键词开始搜索

C++ 并发编程

创建线程

#include <thread>
#include <iostream>

void worker(int n) { std::cout << "Thread: " << n << '\n'; }

// 传函数指针
std::thread t1(worker, 42);

// Lambda
std::thread t2([](int a, int b) { std::cout << a + b; }, 3, 5);

// 成员函数
struct Task { void run() { /*...*/ } };
Task task;
std::thread t3(&Task::run, &task);

// 必须 join 或 detach
t1.join();   // 等待线程结束
t2.detach(); // 分离(后台运行,不 join —— 谨慎使用)

// ⚠️ 析构时未 join/detach 的 thread → std::terminate

std::mutex — 互斥锁

#include <mutex>

std::mutex mtx;
int counter = 0;

void increment() {
    std::lock_guard<std::mutex> lock(mtx);  // RAII 自动解锁
    ++counter;
}  // lock 析构 → 自动 mtx.unlock()

// lock_guard vs unique_lock
std::lock_guard<std::mutex> lg(mtx);       // 构造锁定,不可手动解锁
std::unique_lock<std::mutex> ul(mtx);      // 可手动 ul.unlock() / ul.lock()
std::unique_lock<std::mutex> ul2(mtx, std::defer_lock); // 构造不锁
ul2.lock();    // 手动锁
ul2.unlock();  // 手动解锁

// 同时锁多个 mutex(避免死锁)
std::scoped_lock lock(mtx1, mtx2);  // C++17

condition_variable — 条件变量

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

// 等待方
void consumer() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });  // 等待 ready == true
    // do work...
}

// 通知方
void producer() {
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    cv.notify_one();  // 唤醒一个等待者
    // cv.notify_all(); // 唤醒所有
}

std::atomic — 无锁原子操作

#include <atomic>

std::atomic<int> ai{0};      // 原子整型
std::atomic<bool> flag{false};

ai.fetch_add(1);             // 原子 +1
ai.store(42);                // 原子写入
int val = ai.load();         // 原子读取

// CAS(Compare-And-Swap)
int expected = 0;
if (ai.compare_exchange_strong(expected, 1)) {
    // 成功:ai 从 0 变为 1
} else {
    // 失败:ai 不是 0,expected 被更新为 ai 当前值
}

// memory order(默认 sequential consistency,安全但略慢)
ai.store(42, std::memory_order_relaxed);  // 无同步要求
ai.store(42, std::memory_order_release);  // 释放语义
ai.load(std::memory_order_acquire);       // 获取语义

std::async 与 std::future

#include <future>

// 异步执行,返回 future
std::future<int> result = std::async(std::launch::async, []() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 42;
});

// 获取结果(阻塞直到完成)
int val = result.get();  // 42
// ⚠️ get() 只能调一次,第二次抛异常

// 共享 future
std::shared_future<int> sf = result.share();
// sf.get() 可多次调用

// promise → future
std::promise<int> promise;
std::future<int> future = promise.get_future();

std::thread([&promise]() {
    promise.set_value(100);  // 设置结果
}).detach();

int res = future.get();  // 100

线程安全模式

单例 double-check

class Singleton {
    static std::atomic<Singleton *> instance;
    static std::mutex mtx;
public:
    static Singleton *get() {
        Singleton *p = instance.load(std::memory_order_acquire);
        if (!p) {
            std::lock_guard lock(mtx);
            p = instance.load(std::memory_order_relaxed);
            if (!p) {
                p = new Singleton();
                instance.store(p, std::memory_order_release);
            }
        }
        return p;
    }
};
// C++11+: 函数内 static 本身就是线程安全的
Singleton &get() { static Singleton s; return s; }

读写锁

#include <shared_mutex>

std::shared_mutex rwMtx;

// 读(共享锁,多线程可同时读)
void read() {
    std::shared_lock lock(rwMtx);
    // 读取共享数据...
}

// 写(独占锁)
void write() {
    std::unique_lock lock(rwMtx);
    // 修改共享数据...
}

速查

工具用途
std::thread创建线程
std::mutex + lock_guard互斥保护
std::scoped_lock多锁同时锁定
std::condition_variable等待/通知
std::atomic无锁原子变量
std::async / future异步任务返回值
std::shared_mutex读写锁
thread_local线程局部存储