在 Ubuntu(Linux)下用 C++ 写多线程,主要有 三种常见方式:
std::thread)✅ 简单、跨平台、现代 C++ 首选
#include <iostream>
#include <thread>
void thread_func(int id) {
std::cout << "线程 " << id << " 运行中\n";
}
int main() {
std::thread t1(thread_func, 1);
std::thread t2(thread_func, 2);
t1.join();
t2.join();
return 0;
}
g++ main.cpp -std=c++11 -pthread
./a.out
⚠️
-pthread是必须的
✅ 更接近系统层,老项目常见
#include <pthread.h>
#include <iostream>
void* thread_func(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, thread_func, &a);
pthread_create(&t2, nullptr, thread_func, &b);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
}
g++ main.cpp -pthread
#include <mutex>
std::mutex mtx;
void safe_print() {
mtx.lock();
std::cout << "安全输出\n";
mtx.unlock();
}
或用 RAII:
std::lock_guard<std::mutex> lock(mtx);
std::condition_variable cv;
❓ 为什么不用 fork?
fork 是进程,不是线程❓ 线程数多少合适?
std::threadmutex / lock_guardcondition_variableasync / future如果你愿意,我可以:
你现在是学习用还是项目实战?