在 Ubuntu 下用 C++ 写多线程,常见有三种方式:
std::thread)✅ 推荐下面重点讲 C++11 的写法,最常用也最现代。
std::thread(推荐)#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "Thread " << id << " is running\n";
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
std::cout << "Main thread done\n";
return 0;
}
g++ thread_demo.cpp -std=c++11 -pthread -o thread_demo
./thread_demo
⚠️ 必须加
-pthread
std::mutex#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int counter = 0;
void increment() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
++counter;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Counter = " << counter << std::endl;
}
std::thread t([] {
std::cout << "Lambda thread\n";
});
t.join();
#include <pthread.h>
#include <iostream>
void* worker(void* arg) {
std::cout << "pthread\n";
return nullptr;
}
int main() {
pthread_t t;
pthread_create(&t, nullptr, worker, nullptr);
pthread_join(t, nullptr);
}
编译:
g++ pthread_demo.cpp -pthread
✅ 必须加 -pthread
✅ 不要忘记 join() 或 detach()
✅ 多线程访问共享变量要加锁
✅ std::cout 本身不是线程安全的(建议加锁)
std::asyncstd::condition_variablestd::atomic如果你愿意,我可以:
你现在是做 服务器 / 算法 / 嵌入式 哪一块?