在 Ubuntu 上使用 C++ 多线程,通常有两种常见方式:
std::thread) ✅(推荐)下面以 C++11 std::thread 为主讲,最常用、最现代。
sudo apt update
sudo apt install g++ build-essential
查看版本:
g++ --version
#include <iostream>
#include <thread>
void hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(hello);
t.join(); // 等待线程结束
return 0;
}
-pthread)g++ main.cpp -o main -pthread
运行:
./main
#include <iostream>
#include <thread>
void print(int n, const std::string& s) {
std::cout << s << ": " << n << std::endl;
}
int main() {
std::thread t(print, 10, "value");
t.join();
}
#include <iostream>
#include <thread>
#include <vector>
void work(int id) {
std::cout << "Thread " << id << " running\n";
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(work, i);
}
for (auto& t : threads) {
t.join();
}
}
std::mutex#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int counter = 0;
void increment() {
for (int i = 0; i < 10000; ++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;
}
join()terminate called without an active exception
✅ 解决:线程结束前必须 join() 或 detach()
-pthreadundefined reference to `pthread_create`
✅ 编译加:
-pthread
#include <pthread.h>
#include <iostream>
void* run(void*) {
std::cout << "pthread\n";
return nullptr;
}
int main() {
pthread_t t;
pthread_create(&t, nullptr, run, nullptr);
pthread_join(t, nullptr);
}
编译:
g++ p.cpp -o p -pthread
std::asyncstd::futurestd::atomic如果你有 具体需求(比如:网络、计算加速、GUI、生产者消费者),我可以给你更针对性的示例。