在 Linux 下用 C++ 实现“并发”,常见有 多进程、多线程、异步 I/O、协程 等方式。下面按实用程度和常见场景给你一个清晰总结。
#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
✅ 优点:轻量、控制精细
❌ 缺点:手动管理锁、容易出错
#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++ 首选
#include <unistd.h>
#include <iostream>
int main() {
pid_t pid = fork();
if (pid == 0) {
std::cout << "child\n";
} else {
std::cout << "parent\n";
}
}
✅ 稳定、隔离好
❌ 开销大
适合:
int epfd = epoll_create(1);
配合:
#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);
};
优点:
#include <coroutine>
✅ 极高并发
❌ 编译器 / 生态要求较高
| 场景 | 推荐 |
|---|---|
| 普通并发 | std::thread |
| CPU 密集 | 多进程 / 线程池 |
| 网络高并发 | epoll + 线程池 |
| 简单异步 | std::async |
| 极致性能 | 协程 |
如果你愿意,我可以:
你可以告诉我:你是做网络、计算、还是学习用?