在 CentOS 下用 C++ 配置和使用多线程,通常有两种主流方式:
std::thread)(推荐,现代 C++)下面分别说明,并给出编译方式。
std::thread(推荐)#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "Thread " << id << " is running\n";
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
return 0;
}
g++ -std=c++11 -pthread thread_demo.cpp -o thread_demo
⚠️
-pthread很重要,既加编译参数也加链接参数
./thread_demo
#include <iostream>
#include <pthread.h>
void* worker(void* arg) {
long id = (long)arg;
std::cout << "pthread " << id << "\n";
return nullptr;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, nullptr, worker, (void*)1);
pthread_create(&t2, nullptr, worker, (void*)2);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
return 0;
}
g++ pthread_demo.cpp -o pthread_demo -lpthread
gcc --version
g++ --version
若版本过低(< 4.8),建议升级:
yum install centos-release-scl
yum install devtoolset-9
scl enable devtoolset-9 bash
#include <thread>
std::thread::hardware_concurrency();
或者命令行:
nproc
std::thread not found-std=c++11-pthreadundefined reference to pthread_*-pthread 或 -lpthread✅ 新项目:用 std::thread
✅ 老系统 / C 接口:用 pthread
✅ 编译必加:-pthread
如果你有 具体场景(如线程池、生产者消费者、锁、CentOS 7/8),我可以给你更完整的示例。