在 Debian 系统上,使用 GCC 支持多线程通常有两种主要方式:POSIX 线程(pthread) 和 C++11 及以上标准线程(std::thread)。下面分别说明。
一般 Debian 默认已安装 GCC 和 glibc(包含 pthread),无需额外安装。
检查 GCC:
gcc --version
#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;
}
必须链接 pthread 库:
gcc test.c -o test -pthread
⚠️ 推荐用
-pthread而不是-lpthread,因为它同时设置编译和链接选项。
std::thread#include <iostream>
#include <thread>
void func() {
std::cout << "Hello from std::thread\n";
}
int main() {
std::thread t(func);
t.join();
}
g++ test.cpp -o test -std=c++11 -pthread
即使使用
std::thread,在 Linux 上底层仍是 pthread,仍需-pthread。
如果你只是想做并行计算:
#include <omp.h>
#include <stdio.h>
int main() {
#pragma omp parallel
printf("Hello from thread %d\n", omp_get_thread_num());
}
编译:
gcc test.c -fopenmp
undefined reference to pthread_create✅ 忘记加 -pthread
可安装:
sudo apt update
sudo apt install build-essential
| 方式 | 编译命令 |
|---|---|
| pthread © | gcc x.c -pthread |
| std::thread (C++) | g++ x.cpp -std=c++11 -pthread |
| OpenMP | gcc x.c -fopenmp |
如果你有具体语言(C / C++)或使用场景(服务器、嵌入式等),我可以给你更针对性的示例。