温馨提示×

centos gcc多线程怎么开启

小樊
38
2026-09-24 00:48:07
栏目: 智能运维

在 CentOS 上使用 GCC 编译多线程程序,通常有两种常见方式:POSIX 线程(pthread) 和 C++11 及以上线程(std::thread)。下面分别说明。


一、使用 pthread(最经典方式)

1️⃣ 写示例程序

// test.c
#include <pthread.h>
#include <stdio.h>

void* thread_func(void* arg) {
    printf("Hello from thread\n");
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    pthread_join(tid, NULL);
    return 0;
}

2️⃣ 编译时开启多线程

gcc test.c -o test -pthread

✅ 关键点

  • -pthread:同时定义宏并链接线程库(推荐)
  • 不要只写 -lpthread(旧方式,某些情况不完整)

二、使用 C++11 std::thread

1️⃣ 示例代码

// test.cpp
#include <thread>
#include <iostream>

void func() {
    std::cout << "Hello from thread\n";
}

int main() {
    std::thread t(func);
    t.join();
}

2️⃣ 编译方式

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

✅ 注意

  • 必须加 -pthread
  • -std=c++11 或更高(c++14 / c++17)

三、OpenMP(并行计算常用)

示例

// omp.c
#include <omp.h>
#include <stdio.h>

int main() {
    #pragma omp parallel
    {
        printf("Hello from thread %d\n", omp_get_thread_num());
    }
}

编译

gcc omp.c -o omp -fopenmp

四、常见问题排查

❌ 报错:undefined reference to pthread_create

✅ 原因:没加 -pthread

❌ CentOS 默认 GCC 太旧

查看版本:

gcc --version

升级(示例):

yum install centos-release-scl
yum install devtoolset-11-gcc devtoolset-11-gcc-c++
scl enable devtoolset-11 bash

五、总结

方式 编译参数
pthread gcc xx.c -pthread
C++ thread g++ xx.cpp -std=c++11 -pthread
OpenMP gcc xx.c -fopenmp

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

  • 用的是 C 还是 C++
  • CentOS 版本(6 / 7 / 8)
  • 具体报错信息

我可以给你更精确的方案。

0 踩