温馨提示×

centosgcc多线程怎么开启

小樊
32
2026-10-02 19:09:05
栏目: 智能运维

在 CentOS 上使用 GCC 编写并编译多线程程序,通常有两种常见方式:


一、使用 POSIX 线程(pthread,最常用)

1️⃣ 写一个简单的多线程程序

#include <pthread.h>
#include <stdio.h>
#include <unistd.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(老写法,不推荐)

二、使用 C11 标准线程(可选)

#include <threads.h>

编译:

gcc test.c -o test -pthread -std=c11

⚠️ CentOS 默认 glibc 对 C11 threads 支持有限,一般还是用 pthread。


三、OpenMP 多线程(适合科学计算)

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

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

编译:

gcc test.c -o test -fopenmp

运行:

export OMP_NUM_THREADS=4
./test

四、CentOS 环境检查

查看 gcc 版本

gcc --version

安装开发工具(如果没有)

sudo yum groupinstall "Development Tools"

五、常见错误

❌ 忘记加 -pthread

undefined reference to `pthread_create'

❌ 用 gcc 编译 C++ 多线程

g++ test.cpp -o test -pthread

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

  • 用的是 C 还是 C++
  • 想用 pthread / OpenMP / std::thread

我可以给你更具体的示例。

0 踩