在 Ubuntu(Linux)下用 C++ 写多线程,常见有 三种方式:
这是最简单、最通用的方式,不需要额外库。
确保 g++ 支持 C++11 及以上:
g++ --version
编译时加 -pthread:
g++ main.cpp -o main -pthread -std=c++11
#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;
}
std::thread t([]{
std::cout << "lambda 线程\n";
});
t.join();
适合更底层控制,但代码更繁琐。
#include <pthread.h>
#include <iostream>
void* worker(void* arg) {
int id = *(int*)arg;
std::cout << "线程 " << id << "\n";
return nullptr;
}
int main() {
pthread_t t1, t2;
int a = 1, b = 2;
pthread_create(&t1, nullptr, worker, &a);
pthread_create(&t2, nullptr, worker, &b);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
}
编译:
g++ main.cpp -o main -pthread
#include <mutex>
std::mutex mtx;
void safe_print() {
mtx.lock();
std::cout << "安全输出\n";
mtx.unlock();
}
或用 RAII:
std::lock_guard<std::mutex> lock(mtx);
用于线程等待/通知。
join() 或 detach()cout(要用 mutex)-pthreadstd::threadstd::mutexstd::atomicstd::async如果你愿意,我可以:
你更想学哪一种?