在 Linux 下用 C++ 实现多线程,常见做法有三种:
std::thread)✅ 推荐下面从 最常用、最现代 的方式讲起。
std::thread(推荐)#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "Thread " << id << " running\n";
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
return 0;
}
编译(Linux):
g++ -std=c++11 -pthread main.cpp -o main
✅ -pthread 很关键
std::thread t([] {
std::cout << "Lambda thread\n";
});
t.join();
#include <mutex>
std::mutex mtx;
void safe_print(int id) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Thread " << id << "\n";
}
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void consumer() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; });
std::cout << "Consumed\n";
}
void producer() {
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
}
适合 底层 / 老项目
#include <pthread.h>
#include <iostream>
void* thread_func(void* arg) {
int id = *(int*)arg;
std::cout << "pthread " << 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++ pthread_example.cpp -pthread
#include <vector>
#include <thread>
int main() {
std::vector<std::thread> pool;
for (int i = 0; i < 4; ++i) {
pool.emplace_back([i] {
std::cout << "Worker " << i << "\n";
});
}
for (auto& t : pool) t.join();
}
Linux 默认支持多核并行
可用:
nproc
ps -eLf
top -H
std::threadmutex / lock_guardcondition_variableatomic如果你愿意,我可以:
你想看哪一个?