在 Ubuntu 下用 C++ 写多线程,通常有两种主流方式:
std::thread) ✅ 推荐pthread) (偏底层,老项目常见)下面分别给你示例,从简单到实用。
std::thread(最推荐)#include <iostream>
#include <thread>
void hello(int id) {
std::cout << "Hello from thread " << id << std::endl;
}
int main() {
std::thread t1(hello, 1);
std::thread t2(hello, 2);
t1.join();
t2.join();
return 0;
}
g++ thread_demo.cpp -std=c++11 -pthread -o thread_demo
./thread_demo
⚠️
-pthread必须加
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int count = 0;
void work() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
count++;
}
}
int main() {
std::thread t1(work);
std::thread t2(work);
t1.join();
t2.join();
std::cout << "count = " << count << std::endl;
return 0;
}
condition_variable(线程通信)#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return ready; });
std::cout << "Worker started\n";
}
int main() {
std::thread t(worker);
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_all();
t.join();
}
#include <pthread.h>
#include <iostream>
void* run(void* arg) {
std::cout << "pthread running\n";
return nullptr;
}
int main() {
pthread_t t;
pthread_create(&t, nullptr, run, nullptr);
pthread_join(t, nullptr);
}
编译:
g++ pthread_demo.cpp -pthread
✅ 必须 join() 或 detach()
✅ 避免数据竞争(用 mutex)
✅ 不要返回局部变量引用
✅ 多线程调试可用:
gdb ./demo
thread apply all bt
如果你愿意,可以告诉我:
我可以直接给你一套可运行的工程模板。