在 Ubuntu 下写 C++ 多线程,通常有两种常见方式:
<thread>(推荐,简单、跨平台)pthread(Linux 传统方式)下面分别说明,并给出完整示例。
Ubuntu 一般都自带 g++,如果没有:
sudo apt update
sudo apt install g++
#include <iostream>
#include <thread>
using namespace std;
void threadFunc(int id) {
cout << "线程 " << id << " 正在运行" << endl;
}
int main() {
thread t1(threadFunc, 1);
thread t2(threadFunc, 2);
t1.join();
t2.join();
cout << "主线程结束" << endl;
return 0;
}
g++ thread.cpp -std=c++11 -pthread -o thread
./thread
⚠️ -pthread 一定要加
std::async(更简单)#include <iostream>
#include <future>
using namespace std;
int compute(int x) {
return x * x;
}
int main() {
auto f = async(launch::async, compute, 10);
cout << "结果: " << f.get() << endl;
}
编译方式相同。
#include <iostream>
#include <pthread.h>
using namespace std;
void* run(void* arg) {
long id = (long)arg;
cout << "pthread " << id << endl;
return nullptr;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, nullptr, run, (void*)1);
pthread_create(&t2, nullptr, run, (void*)2);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
}
g++ pthread.cpp -pthread -o pthread
mutex#include <iostream>
#include <thread>
#include <mutex>
mutex mtx;
void print(int id) {
mtx.lock();
cout << "线程 " << id << endl;
mtx.unlock();
}
int main() {
thread t1(print, 1);
thread t2(print, 2);
t1.join();
t2.join();
}
❌ 忘了 -pthread
❌ 主线程提前退出(没 join)
❌ 多个线程同时 cout 导致乱序(用 mutex)
如果你愿意,我可以:
你想学哪一种?