在 CentOS 上使用 GCC 编写并编译多线程程序,通常有两种常见方式:
#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;
}
gcc test.c -o test -pthread
✅ 重点:
-pthread-lpthread(老写法,不推荐)#include <threads.h>
编译:
gcc test.c -o test -pthread -std=c11
⚠️ CentOS 默认 glibc 对 C11 threads 支持有限,一般还是用 pthread。
#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
gcc --version
sudo yum groupinstall "Development Tools"
❌ 忘记加 -pthread
undefined reference to `pthread_create'
❌ 用 gcc 编译 C++ 多线程
g++ test.cpp -o test -pthread
如果你愿意,可以告诉我:
我可以给你更具体的示例。