温馨提示×

centos怎么写c++多线程

小樊
47
2026-10-23 13:55:18
栏目: 编程语言

在 CentOS 上写 C++ 多线程程序,一般使用 C++11 标准线程库(std::thread),或者更底层的 POSIX 线程(pthread)。下面我分别给你示例,并说明编译方法。


一、环境准备(CentOS)

1. 安装 GCC(一般 CentOS 自带)

gcc --version
g++ --version

如果版本太低(低于 4.8),建议升级:

sudo yum install centos-release-scl
sudo yum install devtoolset-9
scl enable devtoolset-9 bash

二、使用 C++11 标准线程(推荐 ✅)

示例:简单多线程

#include <iostream>
#include <thread>
#include <vector>

using namespace std;

void worker(int id) {
    cout << "线程 " << id << " 开始执行" << endl;
}

int main() {
    vector<thread> threads;

    for (int i = 0; i < 5; ++i) {
        threads.emplace_back(worker, i);
    }

    for (auto& t : threads) {
        t.join();
    }

    cout << "所有线程结束" << endl;
    return 0;
}

编译(关键 -pthread)

g++ -std=c++11 -pthread main.cpp -o main

运行

./main

三、线程同步(mutex 示例)

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

mutex mtx;

void print(int id) {
    mtx.lock();
    cout << "线程 " << id << " 正在打印" << endl;
    mtx.unlock();
}

int main() {
    thread t1(print, 1);
    thread t2(print, 2);

    t1.join();
    t2.join();
}

四、使用 POSIX 线程(pthread,传统方式)

#include <pthread.h>
#include <iostream>

using namespace std;

void* thread_func(void* arg) {
    long id = (long)arg;
    cout << "pthread " << id << endl;
    return nullptr;
}

int main() {
    pthread_t t1, t2;

    pthread_create(&t1, nullptr, thread_func, (void*)1);
    pthread_create(&t2, nullptr, thread_func, (void*)2);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
}

编译

g++ pthread_demo.cpp -o pthread_demo -pthread

五、常见问题

1. 忘记 -pthread

报错类似:

undefined reference to `pthread_create`

✅ 加 -pthread

2. C++ 版本太低

✅ 使用 -std=c++11 或更高


六、进阶方向(如果你需要)

  • std::async
  • 线程池
  • 原子操作 std::atomic
  • 条件变量 std::condition_variable

如果你愿意,可以告诉我:

  • 你是 学操作系统 / 面试 / 项目开发
  • 需要 Linux 服务器高并发示例

我可以直接给你更贴合的代码。

0 踩