在 CentOS 上配置和使用 C++ 多线程,主要涉及 编译器支持、开发库安装、编译选项 三部分。下面按步骤说明。
CentOS 默认通常已安装 gcc/g++,但版本可能较旧。
g++ --version
gcc --version
<thread>如需升级(可选):
# CentOS 7
yum install centos-release-scl
yum install devtoolset-9-gcc devtoolset-9-gcc-c++
scl enable devtoolset-9 bash
# CentOS 7
yum groupinstall "Development Tools"
yum install gcc-c++ make
# CentOS 8
dnf groupinstall "Development Tools"
dnf install gcc-c++ make
✅ C++ 多线程只需要
pthread,一般系统已自带
thread.cpp#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;
}
⚠️ 必须加 -pthread
g++ -std=c++11 thread.cpp -o thread -pthread
或(等价):
g++ -std=c++11 thread.cpp -o thread -lpthread
运行:
./thread
std::thread not found-std=c++11join() 或 detach()devtoolsetstd::async#include <future>
auto f = std::async(std::launch::async, []{
return 42;
});
gdb ./thread
thread apply all bt
如果你愿意,可以告诉我:
我可以进一步给你 CMake 配置或实际工程示例。