你这个问题“如何在 CentOS 上配置 C++ 多线程”通常包含 三件事:
下面一步一步给你说明。
CentOS 7/8 一般自带 gcc,但版本可能较旧。
# 查看版本
g++ --version
# 如果没装
sudo yum install gcc-c++ -y
多线程需要 C++11 或更高版本
g++ -std=c++11 test.cpp
#include <iostream>
#include <thread>
void foo(int n) {
std::cout << "Thread " << n << std::endl;
}
int main() {
std::thread t1(foo, 1);
std::thread t2(foo, 2);
t1.join();
t2.join();
return 0;
}
-pthreadg++ -std=c++11 -pthread test.cpp -o test
⚠️ 只加
-lpthread在 CentOS 上可能不够,建议用-pthread
运行:
./test
pthread_create原因:没加 -pthread
✅ 解决:
g++ -pthread xxx.cpp
原因:用了 C++98
✅ 解决:
-std=c++11 或 -std=c++14
CentOS 7 默认 gcc 4.8.5(可用)
如果要新版本:
sudo yum install centos-release-scl -y
sudo yum install devtoolset-9 -y
scl enable devtoolset-9 bash
如果你只是想并行循环:
#include <iostream>
#include <omp.h>
int main() {
#pragma omp parallel
{
std::cout << "Hello from thread\n";
}
}
编译:
g++ -fopenmp test.cpp
✅ CentOS + C++ 多线程最小配置:
yum install gcc-c++
g++ -std=c++11 -pthread main.cpp -o main
如果你愿意,可以告诉我:
我可以直接给你一份 可运行的工程模板。