在 Linux 下用 C++ 做多线程,常见有三种方式:POSIX 线程(pthread)、C++11 线程库(推荐)、以及 第三方库。下面从最常用到最底层给你讲清楚,并附示例。
std::thread(现代 C++)优点
#include <iostream>
#include <thread>
void func1() {
std::cout << "Thread 1 running\n";
}
void func2(int x) {
std::cout << "Thread 2, x = " << x << "\n";
}
int main() {
std::thread t1(func1);
std::thread t2(func2, 10);
t1.join(); // 等待线程结束
t2.join();
return 0;
}
g++ -std=c++11 main.cpp -pthread
⚠️ 注意:必须加
-pthread
如果你写偏底层(如系统编程、嵌入式),可能会看到 pthread。
#include <iostream>
#include <pthread.h>
void* thread_func(void* arg) {
std::cout << "pthread running\n";
return nullptr;
}
int main() {
pthread_t t;
pthread_create(&t, nullptr, thread_func, nullptr);
pthread_join(t, nullptr);
return 0;
}
g++ main.cpp -pthread
多线程一定要处理竞态条件。
std::mutex(互斥锁)#include <thread>
#include <mutex>
#include <iostream>
std::mutex mtx;
void func() {
mtx.lock();
std::cout << "safe print\n";
mtx.unlock();
}
int main() {
std::thread t1(func);
std::thread t2(func);
t1.join();
t2.join();
}
✅ 推荐用 std::lock_guard:
std::lock_guard<std::mutex> lock(mtx);
std::condition_variable cv;
std::mutex mtx;
bool ready = false;
void consumer() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; });
}
void producer() {
ready = true;
cv.notify_one();
}
❌ 线程对象析构前没 join 或 detach
std::thread t(func);
// t.join(); 或 t.detach(); // 必须
❌ 多线程同时 cout(要加锁)
❌ 误以为多线程一定更快(线程切换也有开销)
| 场景 | 推荐 |
|---|---|
| 普通 Linux C++ 程序 | ✅ std::thread |
| 系统 / 嵌入式 | pthread |
| 高性能并发 | 线程池 + 无锁队列 |
| 并行计算 | OpenMP / TBB |
如果你要“大量任务 + 少量线程”,我可以给你一个线程池完整示例。
如果你愿意,可以告诉我:
我可以根据你的场景直接给你最合适的代码。