温馨提示×

linux c++怎么实现并发

小樊
38
2026-09-23 09:07:25
栏目: 编程语言

在 Linux 下用 C++ 实现“并发”,常见有 多进程、多线程、异步 I/O、协程 等方式。下面按实用程度常见场景给你一个清晰总结。


一、多线程(最常用 ✅)

1️⃣ 使用 POSIX 线程(pthread)

#include <pthread.h>
#include <iostream>

void* thread_func(void* arg) {
    std::cout << "Hello from thread\n";
    return nullptr;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, nullptr, thread_func, nullptr);
    pthread_join(tid, nullptr);
}

编译:

g++ test.cpp -lpthread

✅ 优点:轻量、控制精细
❌ 缺点:手动管理锁、容易出错


2️⃣ 使用 C++11 标准线程(推荐 ✅✅)

#include <thread>
#include <iostream>

void worker() {
    std::cout << "thread running\n";
}

int main() {
    std::thread t(worker);
    t.join();
}

编译:

g++ test.cpp -std=c++11 -pthread

常用同步工具

std::mutex
std::lock_guard
std::unique_lock
std::condition_variable
std::atomic

✅ 跨平台
✅ 现代 C++ 首选


二、多进程(适合 CPU 密集型 / 隔离性要求高)

1️⃣ fork()

#include <unistd.h>
#include <iostream>

int main() {
    pid_t pid = fork();
    if (pid == 0) {
        std::cout << "child\n";
    } else {
        std::cout << "parent\n";
    }
}

进程间通信(IPC)

  • pipe
  • shared memory
  • message queue
  • socket

✅ 稳定、隔离好
❌ 开销大


三、异步并发(I/O 密集型 ✅)

1️⃣ epoll(高并发网络)

适合:

  • 网络服务器
  • 十万级以上连接
int epfd = epoll_create(1);

配合:

  • non-blocking socket
  • event loop

2️⃣ async(C++11)

#include <future>
#include <iostream>

int compute() { return 42; }

int main() {
    auto f = std::async(std::launch::async, compute);
    std::cout << f.get() << std::endl;
}

✅ 简单
❌ 不适合超大规模并发


四、线程池(工程常用 ✅✅✅)

// 简化示例
class ThreadPool {
public:
    void submit(std::function<void()> task);
};

优点:

  • 避免频繁创建线程
  • 控制并发数
  • 生产级方案

五、协程(C++20,未来趋势)

#include <coroutine>

✅ 极高并发
❌ 编译器 / 生态要求较高


六、如何选择?

场景 推荐
普通并发 std::thread
CPU 密集 多进程 / 线程池
网络高并发 epoll + 线程池
简单异步 std::async
极致性能 协程

七、示例:线程池 + 任务(实战)

如果你愿意,我可以:

  • ✅ 写一个 完整线程池
  • ✅ 写一个 epoll 服务器
  • ✅ 对比 pthread vs std::thread
  • ✅ 讲 锁 / 死锁 / 原子操作

你可以告诉我:你是做网络、计算、还是学习用?

0