在 Ubuntu 下用 C++ 写多线程,常见有 三种方式:
std::thread)✅ 推荐下面重点讲 最常用、最现代的 std::thread。
std::thread(推荐)Ubuntu 一般自带 g++,确保版本 ≥ 4.8:
g++ --version
#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "线程 " << id << " 正在运行\n";
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
std::cout << "主线程结束\n";
return 0;
}
-pthread)g++ main.cpp -std=c++11 -pthread -o test
./test
std::mutex#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void count(int id) {
mtx.lock();
std::cout << "线程 " << id << "\n";
mtx.unlock();
}
int main() {
std::thread t1(count, 1);
std::thread t2(count, 2);
t1.join();
t2.join();
}
✅ 更推荐用:
std::lock_guard<std::mutex> lock(mtx);
std::thread t([]{
std::cout << "lambda 线程\n";
});
t.join();
#include <pthread.h>
#include <iostream>
void* run(void*) {
std::cout << "pthread\n";
return nullptr;
}
int main() {
pthread_t t;
pthread_create(&t, nullptr, run, nullptr);
pthread_join(t, nullptr);
}
编译:
g++ pthread.cpp -pthread
join() 或 detach()terminate called without an active exception
t.join(); // 等线程结束
// 或
t.detach(); // 分离线程(不推荐新手用)
std::asyncstd::futurestd::condition_variable如果你愿意,我可以:
✅ 写 线程池示例
✅ 讲 多线程+网络
✅ 对比 多线程 vs 多进程
你现在是学习还是做项目?