linux

C++ Linux下的并发编程模型

小樊
42
2025-11-29 05:39:47
栏目: 编程语言

C++ Linux 并发编程模型全景

一、模型总览与适用场景

二、关键模型要点与对比

模型 编程接口/库 典型场景 优点 局限
多线程共享内存 / pthread 计算并行、共享状态 易理解、控制力强 数据竞争、死锁风险、同步复杂
Future/Promise / 任务并发、延迟取结果 结果获取简洁、可组合 过度分配线程、结果获取可能阻塞
并行算法 par 数据并行 代码改动小、自动利用多核 负载不均时收益受限、需可并行化
线程池 自定义 + 队列 高吞吐短任务 降低线程创建开销、易控并发度 需合理队列与拒绝策略
事件驱动 + epoll epoll + 回调/协程 高并发 I/O 高可扩展、资源占用低 回调地狱、复杂状态机
协程 / Sender-Receiver C++20 协程 / libunifex 复杂异步编排 可读性强、可取消、组合性强 生态较新、学习曲线、需编译器支持

三、实践建议与常见陷阱

四、最小示例

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

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

void worker(int id) {
    std::unique_lock<std::mutex> lk(mtx);
    cv.wait(lk, []{ return ready; });
    std::cout << "Worker " << id << " running\n";
}

int main() {
    std::thread t1(worker, 1), t2(worker, 2);
    {
        std::lock_guard<std::mutex> lk(mtx);
        ready = true;
    }
    cv.notify_all();
    t1.join(); t2.join();
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>

int main() {
    std::vector<int> v = {1,2,3,4,5};
    std::for_each(std::execution::par, v.begin(), v.end(), [](int& n){ n *= 2; });
    for (int n : v) std::cout << n << ' ';
}
#include <iostream>
#include <thread>
#include <future>

int work(int x) { return x * x; }

int main() {
    std::promise<int> p;
    std::future<int> f = p.get_future();
    std::thread t([p = std::move(p)]() mutable { p.set_value(work(6)); });
    std::cout << "Result: " << f.get() << '\n'; // 36
    t.join();
}
g++ -O2 -std=c++17 -pthread your_file.cpp -o your_app

0
看了该问题的人还看了