在 Linux 下用 C++ 处理线程,常见有 三种层级 的做法,从底层到现代:
Linux 原生线程接口。
#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);
return 0;
}
编译:
g++ main.cpp -lpthread
pthread_createpthread_join(等待)pthread_detach(分离)pthread_mutex_*(互斥锁)pthread_cond_*(条件变量)✅ 优点:贴近系统
❌ 缺点:C 风格,容易出错
#include <thread>
#include <iostream>
void func(int x) {
std::cout << "x = " << x << "\n";
}
int main() {
std::thread t(func, 10);
t.join(); // 必须 join 或 detach
}
编译(C++11+):
g++ main.cpp -std=c++11 -pthread
#include <mutex>
std::mutex mtx;
void safe() {
std::lock_guard<std::mutex> lock(mtx);
// 临界区
}
#include <condition_variable>
std::condition_variable cv;
bool ready = false;
cv.wait(lock, []{ return ready; });
cv.notify_one();
✅ 优点:跨平台、现代、安全
✅ 推荐默认使用
#include <future>
auto f = std::async([]{ return 42; });
int r = f.get();
-pthread
ulimit -u 限制fork() 很危险| 场景 | 推荐 |
|---|---|
| 学习 / 底层 | pthread |
| 普通程序 | std::thread |
| 高性能服务 | 线程池 |
| 简单异步 | std::async |
如果你愿意,我可以:
你现在是哪种使用场景?