在 CentOS 上使用 GCC 编译多线程程序,通常有两种常见方式:POSIX 线程(pthread) 和 C++11 及以上线程(std::thread)。下面分别说明。
// 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;
}
gcc test.c -o test -pthread
✅ 关键点
-pthread:同时定义宏并链接线程库(推荐)-lpthread(旧方式,某些情况不完整)std::thread// test.cpp
#include <thread>
#include <iostream>
void func() {
std::cout << "Hello from thread\n";
}
int main() {
std::thread t(func);
t.join();
}
g++ test.cpp -o test -std=c++11 -pthread
✅ 注意
-pthread-std=c++11 或更高(c++14 / c++17)// 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
查看版本:
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 |
如果你愿意,可以告诉我:
我可以给你更精确的方案。