在 CentOS 上配置和使用 C++ 多线程,通常包含以下几个步骤:
✅ 安装编译环境
✅ 使用 C++11 及以上标准线程库(推荐) 或 POSIX pthread
✅ 编译时正确链接
下面我按最常见、最推荐的方式给你一个完整说明。
cat /etc/centos-release
CentOS 7 / 8 都支持 C++11 多线程,只是编译器版本不同。
sudo yum install -y gcc gcc-c++ make
查看版本:
g++ --version
CentOS 7 默认 gcc 是 4.8.5,支持 C++11(够用)
sudo dnf install -y gcc gcc-c++ make
或安装较新版本:
sudo dnf install gcc-toolset-11
scl enable gcc-toolset-11 bash
#include <iostream>
#include <thread>
void func(int id) {
std::cout << "Thread " << id << " is running\n";
}
int main() {
std::thread t1(func, 1);
std::thread t2(func, 2);
t1.join();
t2.join();
return 0;
}
✅ 必须加 -std=c++11 或更高
✅ 必须加 -pthread
g++ -std=c++11 -pthread main.cpp -o main
运行:
./main
-pthread?-pthread 会:
_REENTRANTstd::thread 正确工作⚠️ 不要只写 -lpthread,在某些系统上不生效。
如果你看到老代码用 pthread_create:
#include <pthread.h>
#include <iostream>
void* thread_func(void* arg) {
std::cout << "pthread running\n";
return nullptr;
}
int main() {
pthread_t t;
pthread_create(&t, nullptr, thread_func, nullptr);
pthread_join(t, nullptr);
}
编译:
g++ main.cpp -o main -pthread
std::thread not found✅ 原因:没加 -std=c++11
Enable multithreading to use std::thread✅ 原因:没加 -pthread
✅ 可升级 gcc:
yum install centos-release-scl
yum install devtoolset-11
scl enable devtoolset-11 bash
| 项目 | 推荐 |
|---|---|
| 线程库 | std::thread |
| 标准 | C++11 / C++17 |
| 编译器 | gcc ≥ 7 |
| 构建工具 | cmake / make |
你现在是 CentOS 几? 用的是 yum 还是 dnf?