温馨提示×

centos怎么配置c++多线程

小樊
35
2026-07-20 11:16:11
栏目: 编程语言

CentOS 上配置和使用 C++ 多线程,通常包含以下几个步骤:
✅ 安装编译环境
✅ 使用 C++11 及以上标准线程库(推荐)POSIX pthread
✅ 编译时正确链接

下面我按最常见、最推荐的方式给你一个完整说明。


一、确认 CentOS 版本(建议)

cat /etc/centos-release

CentOS 7 / 8 都支持 C++11 多线程,只是编译器版本不同。


二、安装 C++ 编译环境

1️⃣ CentOS 7

sudo yum install -y gcc gcc-c++ make

查看版本:

g++ --version

CentOS 7 默认 gcc 是 4.8.5,支持 C++11(够用)


2️⃣ CentOS 8 / Stream

sudo dnf install -y gcc gcc-c++ make

或安装较新版本:

sudo dnf install gcc-toolset-11
scl enable gcc-toolset-11 bash

三、使用 C++11 多线程(✅ 推荐)

示例:多线程程序

#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 会:
    • 定义 _REENTRANT
    • 链接正确的线程库
    • 保证 std::thread 正确工作

⚠️ 不要只写 -lpthread,在某些系统上不生效。


五、使用 POSIX pthread(不推荐新项目)

如果你看到老代码用 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


❌ CentOS 7 编译太老

✅ 可升级 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

八、如果你愿意,我可以继续帮你:

  • ✅ 写一个 线程池
  • ✅ 讲 线程同步(mutex / condition_variable)
  • ✅ 用 cmake 配置多线程项目
  • ✅ 分析 多线程性能问题

你现在是 CentOS 几? 用的是 yum 还是 dnf?

0